blob: 87150a90b1ff5440680060a129615fded98358ed [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100159 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 CHECK_SMALL_INT(ival);
161 }
162 result = _PyLong_New(i);
163 if (result != NULL) {
164 Py_SIZE(result) = Py_SIZE(src);
165 while (--i >= 0)
166 result->ob_digit[i] = src->ob_digit[i];
167 }
168 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000169}
170
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000171/* Create a new long int object from a C long int */
172
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000174PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyLongObject *v;
177 unsigned long abs_ival;
178 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
179 int ndigits = 0;
180 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (ival < 0) {
185 /* negate: can't write this as abs_ival = -ival since that
186 invokes undefined behaviour when ival is LONG_MIN */
187 abs_ival = 0U-(unsigned long)ival;
188 sign = -1;
189 }
190 else {
191 abs_ival = (unsigned long)ival;
192 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 /* Fast path for single-digit ints */
195 if (!(abs_ival >> PyLong_SHIFT)) {
196 v = _PyLong_New(1);
197 if (v) {
198 Py_SIZE(v) = sign;
199 v->ob_digit[0] = Py_SAFE_DOWNCAST(
200 abs_ival, unsigned long, digit);
201 }
202 return (PyObject*)v;
203 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000204
Mark Dickinson249b8982009-04-27 19:41:00 +0000205#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* 2 digits */
207 if (!(abs_ival >> 2*PyLong_SHIFT)) {
208 v = _PyLong_New(2);
209 if (v) {
210 Py_SIZE(v) = 2*sign;
211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
215 }
216 return (PyObject*)v;
217 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000218#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Larger numbers: loop to determine number of digits */
221 t = abs_ival;
222 while (t) {
223 ++ndigits;
224 t >>= PyLong_SHIFT;
225 }
226 v = _PyLong_New(ndigits);
227 if (v != NULL) {
228 digit *p = v->ob_digit;
229 Py_SIZE(v) = ndigits*sign;
230 t = abs_ival;
231 while (t) {
232 *p++ = Py_SAFE_DOWNCAST(
233 t & PyLong_MASK, unsigned long, digit);
234 t >>= PyLong_SHIFT;
235 }
236 }
237 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238}
239
Guido van Rossum53756b11997-01-03 17:14:46 +0000240/* Create a new long int object from a C unsigned long int */
241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long t;
247 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (ival < PyLong_BASE)
250 return PyLong_FromLong(ival);
251 /* Count the number of Python digits. */
252 t = (unsigned long)ival;
253 while (t) {
254 ++ndigits;
255 t >>= PyLong_SHIFT;
256 }
257 v = _PyLong_New(ndigits);
258 if (v != NULL) {
259 digit *p = v->ob_digit;
260 Py_SIZE(v) = ndigits;
261 while (ival) {
262 *p++ = (digit)(ival & PyLong_MASK);
263 ival >>= PyLong_SHIFT;
264 }
265 }
266 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267}
268
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269/* Create a new long int object from a C double */
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyLongObject *v;
275 double frac;
276 int i, ndig, expo, neg;
277 neg = 0;
278 if (Py_IS_INFINITY(dval)) {
279 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000280 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return NULL;
282 }
283 if (Py_IS_NAN(dval)) {
284 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000285 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return NULL;
287 }
288 if (dval < 0.0) {
289 neg = 1;
290 dval = -dval;
291 }
292 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
293 if (expo <= 0)
294 return PyLong_FromLong(0L);
295 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
296 v = _PyLong_New(ndig);
297 if (v == NULL)
298 return NULL;
299 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
300 for (i = ndig; --i >= 0; ) {
301 digit bits = (digit)frac;
302 v->ob_digit[i] = bits;
303 frac = frac - (double)bits;
304 frac = ldexp(frac, PyLong_SHIFT);
305 }
306 if (neg)
307 Py_SIZE(v) = -(Py_SIZE(v));
308 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309}
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
312 * anything about what happens when a signed integer operation overflows,
313 * and some compilers think they're doing you a favor by being "clever"
314 * then. The bit pattern for the largest postive signed long is
315 * (unsigned long)LONG_MAX, and for the smallest negative signed long
316 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
317 * However, some other compilers warn about applying unary minus to an
318 * unsigned operand. Hence the weird "0-".
319 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
321#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322
Mark Dickinson8d48b432011-10-23 20:47:14 +0100323/* Get a C long int from a long int object or any object that has an __int__
324 method.
325
326 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
327 the result. Otherwise *overflow is 0.
328
329 For other errors (e.g., TypeError), return -1 and set an error condition.
330 In this case *overflow will be 0.
331*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000332
333long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000334PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* This version by Tim Peters */
337 register PyLongObject *v;
338 unsigned long x, prev;
339 long res;
340 Py_ssize_t i;
341 int sign;
342 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 *overflow = 0;
345 if (vv == NULL) {
346 PyErr_BadInternalCall();
347 return -1;
348 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!PyLong_Check(vv)) {
351 PyNumberMethods *nb;
352 nb = vv->ob_type->tp_as_number;
353 if (nb == NULL || nb->nb_int == NULL) {
354 PyErr_SetString(PyExc_TypeError,
355 "an integer is required");
356 return -1;
357 }
358 vv = (*nb->nb_int) (vv);
359 if (vv == NULL)
360 return -1;
361 do_decref = 1;
362 if (!PyLong_Check(vv)) {
363 Py_DECREF(vv);
364 PyErr_SetString(PyExc_TypeError,
365 "nb_int should return int object");
366 return -1;
367 }
368 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 res = -1;
371 v = (PyLongObject *)vv;
372 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 switch (i) {
375 case -1:
376 res = -(sdigit)v->ob_digit[0];
377 break;
378 case 0:
379 res = 0;
380 break;
381 case 1:
382 res = v->ob_digit[0];
383 break;
384 default:
385 sign = 1;
386 x = 0;
387 if (i < 0) {
388 sign = -1;
389 i = -(i);
390 }
391 while (--i >= 0) {
392 prev = x;
393 x = (x << PyLong_SHIFT) | v->ob_digit[i];
394 if ((x >> PyLong_SHIFT) != prev) {
395 *overflow = sign;
396 goto exit;
397 }
398 }
399 /* Haven't lost any bits, but casting to long requires extra
400 * care (see comment above).
401 */
402 if (x <= (unsigned long)LONG_MAX) {
403 res = (long)x * sign;
404 }
405 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
406 res = LONG_MIN;
407 }
408 else {
409 *overflow = sign;
410 /* res is already set to -1 */
411 }
412 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (do_decref) {
415 Py_DECREF(vv);
416 }
417 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000418}
419
Mark Dickinson8d48b432011-10-23 20:47:14 +0100420/* Get a C long int from a long int object or any object that has an __int__
421 method. Return -1 and set an error if overflow occurs. */
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000424PyLong_AsLong(PyObject *obj)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 int overflow;
427 long result = PyLong_AsLongAndOverflow(obj, &overflow);
428 if (overflow) {
429 /* XXX: could be cute and give a different
430 message for overflow == -1 */
431 PyErr_SetString(PyExc_OverflowError,
432 "Python int too large to convert to C long");
433 }
434 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000435}
436
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000437/* Get a Py_ssize_t from a long int object.
438 Returns -1 and sets an error condition if overflow occurs. */
439
440Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000441PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 register PyLongObject *v;
443 size_t x, prev;
444 Py_ssize_t i;
445 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (vv == NULL) {
448 PyErr_BadInternalCall();
449 return -1;
450 }
451 if (!PyLong_Check(vv)) {
452 PyErr_SetString(PyExc_TypeError, "an integer is required");
453 return -1;
454 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 v = (PyLongObject *)vv;
457 i = Py_SIZE(v);
458 switch (i) {
459 case -1: return -(sdigit)v->ob_digit[0];
460 case 0: return 0;
461 case 1: return v->ob_digit[0];
462 }
463 sign = 1;
464 x = 0;
465 if (i < 0) {
466 sign = -1;
467 i = -(i);
468 }
469 while (--i >= 0) {
470 prev = x;
471 x = (x << PyLong_SHIFT) | v->ob_digit[i];
472 if ((x >> PyLong_SHIFT) != prev)
473 goto overflow;
474 }
475 /* Haven't lost any bits, but casting to a signed type requires
476 * extra care (see comment above).
477 */
478 if (x <= (size_t)PY_SSIZE_T_MAX) {
479 return (Py_ssize_t)x * sign;
480 }
481 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
482 return PY_SSIZE_T_MIN;
483 }
484 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000485
Mark Dickinson22b20182010-05-10 21:27:53 +0000486 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyErr_SetString(PyExc_OverflowError,
488 "Python int too large to convert to C ssize_t");
489 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000490}
491
Guido van Rossumd8c80482002-08-13 00:24:58 +0000492/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000493 Returns -1 and sets an error condition if overflow occurs. */
494
495unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000496PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 register PyLongObject *v;
499 unsigned long x, prev;
500 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (vv == NULL) {
503 PyErr_BadInternalCall();
504 return (unsigned long)-1;
505 }
506 if (!PyLong_Check(vv)) {
507 PyErr_SetString(PyExc_TypeError, "an integer is required");
508 return (unsigned long)-1;
509 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 v = (PyLongObject *)vv;
512 i = Py_SIZE(v);
513 x = 0;
514 if (i < 0) {
515 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000516 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return (unsigned long) -1;
518 }
519 switch (i) {
520 case 0: return 0;
521 case 1: return v->ob_digit[0];
522 }
523 while (--i >= 0) {
524 prev = x;
525 x = (x << PyLong_SHIFT) | v->ob_digit[i];
526 if ((x >> PyLong_SHIFT) != prev) {
527 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000528 "python int too large to convert "
529 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return (unsigned long) -1;
531 }
532 }
533 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000534}
535
Stefan Krahb77c6c62011-09-12 16:22:47 +0200536/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
537 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538
539size_t
540PyLong_AsSize_t(PyObject *vv)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 register PyLongObject *v;
543 size_t x, prev;
544 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (vv == NULL) {
547 PyErr_BadInternalCall();
548 return (size_t) -1;
549 }
550 if (!PyLong_Check(vv)) {
551 PyErr_SetString(PyExc_TypeError, "an integer is required");
552 return (size_t)-1;
553 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 v = (PyLongObject *)vv;
556 i = Py_SIZE(v);
557 x = 0;
558 if (i < 0) {
559 PyErr_SetString(PyExc_OverflowError,
560 "can't convert negative value to size_t");
561 return (size_t) -1;
562 }
563 switch (i) {
564 case 0: return 0;
565 case 1: return v->ob_digit[0];
566 }
567 while (--i >= 0) {
568 prev = x;
569 x = (x << PyLong_SHIFT) | v->ob_digit[i];
570 if ((x >> PyLong_SHIFT) != prev) {
571 PyErr_SetString(PyExc_OverflowError,
572 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200573 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 }
575 }
576 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000577}
578
Thomas Hellera4ea6032003-04-17 18:55:45 +0000579/* Get a C unsigned long int from a long int object, ignoring the high bits.
580 Returns -1 and sets an error condition if an error occurs. */
581
Guido van Rossumddefaf32007-01-14 03:31:43 +0000582static unsigned long
583_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 register PyLongObject *v;
586 unsigned long x;
587 Py_ssize_t i;
588 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (vv == NULL || !PyLong_Check(vv)) {
591 PyErr_BadInternalCall();
592 return (unsigned long) -1;
593 }
594 v = (PyLongObject *)vv;
595 i = Py_SIZE(v);
596 switch (i) {
597 case 0: return 0;
598 case 1: return v->ob_digit[0];
599 }
600 sign = 1;
601 x = 0;
602 if (i < 0) {
603 sign = -1;
604 i = -i;
605 }
606 while (--i >= 0) {
607 x = (x << PyLong_SHIFT) | v->ob_digit[i];
608 }
609 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000610}
611
Guido van Rossumddefaf32007-01-14 03:31:43 +0000612unsigned long
613PyLong_AsUnsignedLongMask(register PyObject *op)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyNumberMethods *nb;
616 PyLongObject *lo;
617 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (op && PyLong_Check(op))
620 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
623 nb->nb_int == NULL) {
624 PyErr_SetString(PyExc_TypeError, "an integer is required");
625 return (unsigned long)-1;
626 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 lo = (PyLongObject*) (*nb->nb_int) (op);
629 if (lo == NULL)
630 return (unsigned long)-1;
631 if (PyLong_Check(lo)) {
632 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
633 Py_DECREF(lo);
634 if (PyErr_Occurred())
635 return (unsigned long)-1;
636 return val;
637 }
638 else
639 {
640 Py_DECREF(lo);
641 PyErr_SetString(PyExc_TypeError,
642 "nb_int should return int object");
643 return (unsigned long)-1;
644 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645}
646
Tim Peters5b8132f2003-01-31 15:52:05 +0000647int
648_PyLong_Sign(PyObject *vv)
649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 assert(v != NULL);
653 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000656}
657
Tim Petersbaefd9e2003-01-28 20:37:45 +0000658size_t
659_PyLong_NumBits(PyObject *vv)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyLongObject *v = (PyLongObject *)vv;
662 size_t result = 0;
663 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 assert(v != NULL);
666 assert(PyLong_Check(v));
667 ndigits = ABS(Py_SIZE(v));
668 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
669 if (ndigits > 0) {
670 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100671 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100673 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 do {
675 ++result;
676 if (result == 0)
677 goto Overflow;
678 msd >>= 1;
679 } while (msd);
680 }
681 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000682
Mark Dickinson22b20182010-05-10 21:27:53 +0000683 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
685 "to express in a platform size_t");
686 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000687}
688
Tim Peters2a9b3672001-06-11 21:23:58 +0000689PyObject *
690_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000692{
Mark Dickinson22b20182010-05-10 21:27:53 +0000693 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 int incr; /* direction to move pstartbyte */
695 const unsigned char* pendbyte; /* MSB of bytes */
696 size_t numsignificantbytes; /* number of bytes that matter */
697 Py_ssize_t ndigits; /* number of Python long digits */
698 PyLongObject* v; /* result */
699 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (n == 0)
702 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (little_endian) {
705 pstartbyte = bytes;
706 pendbyte = bytes + n - 1;
707 incr = 1;
708 }
709 else {
710 pstartbyte = bytes + n - 1;
711 pendbyte = bytes;
712 incr = -1;
713 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (is_signed)
716 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200719 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 is positive, and leading 0xff bytes if negative. */
721 {
722 size_t i;
723 const unsigned char* p = pendbyte;
724 const int pincr = -incr; /* search MSB to LSB */
725 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 for (i = 0; i < n; ++i, p += pincr) {
728 if (*p != insignficant)
729 break;
730 }
731 numsignificantbytes = n - i;
732 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
733 actually has 2 significant bytes. OTOH, 0xff0001 ==
734 -0x00ffff, so we wouldn't *need* to bump it there; but we
735 do for 0xffff = -0x0001. To be safe without bothering to
736 check every case, bump it regardless. */
737 if (is_signed && numsignificantbytes < n)
738 ++numsignificantbytes;
739 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* How many Python long digits do we need? We have
742 8*numsignificantbytes bits, and each Python long digit has
743 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
744 /* catch overflow before it happens */
745 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
746 PyErr_SetString(PyExc_OverflowError,
747 "byte array too long to convert to int");
748 return NULL;
749 }
750 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
751 v = _PyLong_New(ndigits);
752 if (v == NULL)
753 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 /* Copy the bits over. The tricky parts are computing 2's-comp on
756 the fly for signed numbers, and dealing with the mismatch between
757 8-bit bytes and (probably) 15-bit Python digits.*/
758 {
759 size_t i;
760 twodigits carry = 1; /* for 2's-comp calculation */
761 twodigits accum = 0; /* sliding register */
762 unsigned int accumbits = 0; /* number of bits in accum */
763 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
766 twodigits thisbyte = *p;
767 /* Compute correction for 2's comp, if needed. */
768 if (is_signed) {
769 thisbyte = (0xff ^ thisbyte) + carry;
770 carry = thisbyte >> 8;
771 thisbyte &= 0xff;
772 }
773 /* Because we're going LSB to MSB, thisbyte is
774 more significant than what's already in accum,
775 so needs to be prepended to accum. */
776 accum |= (twodigits)thisbyte << accumbits;
777 accumbits += 8;
778 if (accumbits >= PyLong_SHIFT) {
779 /* There's enough to fill a Python digit. */
780 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000781 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 ++idigit;
783 accum >>= PyLong_SHIFT;
784 accumbits -= PyLong_SHIFT;
785 assert(accumbits < PyLong_SHIFT);
786 }
787 }
788 assert(accumbits < PyLong_SHIFT);
789 if (accumbits) {
790 assert(idigit < ndigits);
791 v->ob_digit[idigit] = (digit)accum;
792 ++idigit;
793 }
794 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 Py_SIZE(v) = is_signed ? -idigit : idigit;
797 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000798}
799
800int
801_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 unsigned char* bytes, size_t n,
803 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000806 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000808 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
810 digit carry; /* for computing 2's-comp */
811 size_t j; /* # bytes filled */
812 unsigned char* p; /* pointer to next byte in bytes */
813 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (Py_SIZE(v) < 0) {
818 ndigits = -(Py_SIZE(v));
819 if (!is_signed) {
820 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000821 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return -1;
823 }
824 do_twos_comp = 1;
825 }
826 else {
827 ndigits = Py_SIZE(v);
828 do_twos_comp = 0;
829 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (little_endian) {
832 p = bytes;
833 pincr = 1;
834 }
835 else {
836 p = bytes + n - 1;
837 pincr = -1;
838 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 /* Copy over all the Python digits.
841 It's crucial that every Python digit except for the MSD contribute
842 exactly PyLong_SHIFT bits to the total, so first assert that the long is
843 normalized. */
844 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
845 j = 0;
846 accum = 0;
847 accumbits = 0;
848 carry = do_twos_comp ? 1 : 0;
849 for (i = 0; i < ndigits; ++i) {
850 digit thisdigit = v->ob_digit[i];
851 if (do_twos_comp) {
852 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
853 carry = thisdigit >> PyLong_SHIFT;
854 thisdigit &= PyLong_MASK;
855 }
856 /* Because we're going LSB to MSB, thisdigit is more
857 significant than what's already in accum, so needs to be
858 prepended to accum. */
859 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 /* The most-significant digit may be (probably is) at least
862 partly empty. */
863 if (i == ndigits - 1) {
864 /* Count # of sign bits -- they needn't be stored,
865 * although for signed conversion we need later to
866 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000867 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 while (s != 0) {
869 s >>= 1;
870 accumbits++;
871 }
872 }
873 else
874 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Store as many bytes as possible. */
877 while (accumbits >= 8) {
878 if (j >= n)
879 goto Overflow;
880 ++j;
881 *p = (unsigned char)(accum & 0xff);
882 p += pincr;
883 accumbits -= 8;
884 accum >>= 8;
885 }
886 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 /* Store the straggler (if any). */
889 assert(accumbits < 8);
890 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
891 if (accumbits > 0) {
892 if (j >= n)
893 goto Overflow;
894 ++j;
895 if (do_twos_comp) {
896 /* Fill leading bits of the byte with sign bits
897 (appropriately pretending that the long had an
898 infinite supply of sign bits). */
899 accum |= (~(twodigits)0) << accumbits;
900 }
901 *p = (unsigned char)(accum & 0xff);
902 p += pincr;
903 }
904 else if (j == n && n > 0 && is_signed) {
905 /* The main loop filled the byte array exactly, so the code
906 just above didn't get to ensure there's a sign bit, and the
907 loop below wouldn't add one either. Make sure a sign bit
908 exists. */
909 unsigned char msb = *(p - pincr);
910 int sign_bit_set = msb >= 0x80;
911 assert(accumbits == 0);
912 if (sign_bit_set == do_twos_comp)
913 return 0;
914 else
915 goto Overflow;
916 }
Tim Peters05607ad2001-06-13 21:01:27 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Fill remaining bytes with copies of the sign bit. */
919 {
920 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
921 for ( ; j < n; ++j, p += pincr)
922 *p = signbyte;
923 }
Tim Peters05607ad2001-06-13 21:01:27 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000926
Mark Dickinson22b20182010-05-10 21:27:53 +0000927 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
929 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000930
Tim Peters2a9b3672001-06-11 21:23:58 +0000931}
932
Mark Dickinson8d48b432011-10-23 20:47:14 +0100933/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000934
935PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000936PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000937{
Mark Dickinson91044792012-10-18 19:21:43 +0100938#if SIZEOF_VOID_P <= SIZEOF_LONG
939 /* special-case null pointer */
940 if (!p)
941 return PyLong_FromLong(0);
942 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
943#else
944
Tim Peters70128a12001-06-16 08:48:40 +0000945#ifndef HAVE_LONG_LONG
946# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
947#endif
948#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000949# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000950#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* special-case null pointer */
952 if (!p)
953 return PyLong_FromLong(0);
954 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100955#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000956
Guido van Rossum78694d91998-09-18 14:14:13 +0000957}
958
Mark Dickinson8d48b432011-10-23 20:47:14 +0100959/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000960
961void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000962PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000963{
Tim Peters70128a12001-06-16 08:48:40 +0000964#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
968 x = PyLong_AsLong(vv);
969 else
970 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000971#else
Tim Peters70128a12001-06-16 08:48:40 +0000972
973#ifndef HAVE_LONG_LONG
974# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
975#endif
976#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000977# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000978#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
982 x = PyLong_AsLongLong(vv);
983 else
984 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000985
986#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (x == -1 && PyErr_Occurred())
989 return NULL;
990 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000991}
992
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000993#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000994
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000996 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000997 */
998
Tim Peterscf37dfc2001-06-14 18:42:50 +0000999#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +00001000#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001001
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001002/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001003
1004PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001005PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 PyLongObject *v;
1008 unsigned PY_LONG_LONG abs_ival;
1009 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1010 int ndigits = 0;
1011 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 CHECK_SMALL_INT(ival);
1014 if (ival < 0) {
1015 /* avoid signed overflow on negation; see comments
1016 in PyLong_FromLong above. */
1017 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1018 negative = 1;
1019 }
1020 else {
1021 abs_ival = (unsigned PY_LONG_LONG)ival;
1022 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 /* Count the number of Python digits.
1025 We used to pick 5 ("big enough for anything"), but that's a
1026 waste of time and space given that 5*15 = 75 bits are rarely
1027 needed. */
1028 t = abs_ival;
1029 while (t) {
1030 ++ndigits;
1031 t >>= PyLong_SHIFT;
1032 }
1033 v = _PyLong_New(ndigits);
1034 if (v != NULL) {
1035 digit *p = v->ob_digit;
1036 Py_SIZE(v) = negative ? -ndigits : ndigits;
1037 t = abs_ival;
1038 while (t) {
1039 *p++ = (digit)(t & PyLong_MASK);
1040 t >>= PyLong_SHIFT;
1041 }
1042 }
1043 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001044}
1045
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001046/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001047
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001048PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001049PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyLongObject *v;
1052 unsigned PY_LONG_LONG t;
1053 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (ival < PyLong_BASE)
1056 return PyLong_FromLong((long)ival);
1057 /* Count the number of Python digits. */
1058 t = (unsigned PY_LONG_LONG)ival;
1059 while (t) {
1060 ++ndigits;
1061 t >>= PyLong_SHIFT;
1062 }
1063 v = _PyLong_New(ndigits);
1064 if (v != NULL) {
1065 digit *p = v->ob_digit;
1066 Py_SIZE(v) = ndigits;
1067 while (ival) {
1068 *p++ = (digit)(ival & PyLong_MASK);
1069 ival >>= PyLong_SHIFT;
1070 }
1071 }
1072 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001073}
1074
Martin v. Löwis18e16552006-02-15 17:27:45 +00001075/* Create a new long int object from a C Py_ssize_t. */
1076
1077PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001078PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyLongObject *v;
1081 size_t abs_ival;
1082 size_t t; /* unsigned so >> doesn't propagate sign bit */
1083 int ndigits = 0;
1084 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 CHECK_SMALL_INT(ival);
1087 if (ival < 0) {
1088 /* avoid signed overflow when ival = SIZE_T_MIN */
1089 abs_ival = (size_t)(-1-ival)+1;
1090 negative = 1;
1091 }
1092 else {
1093 abs_ival = (size_t)ival;
1094 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 /* Count the number of Python digits. */
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;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001113}
1114
1115/* Create a new long int object from a C size_t. */
1116
1117PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001118PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyLongObject *v;
1121 size_t t;
1122 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +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. */
1127 t = ival;
1128 while (t) {
1129 ++ndigits;
1130 t >>= PyLong_SHIFT;
1131 }
1132 v = _PyLong_New(ndigits);
1133 if (v != NULL) {
1134 digit *p = v->ob_digit;
1135 Py_SIZE(v) = ndigits;
1136 while (ival) {
1137 *p++ = (digit)(ival & PyLong_MASK);
1138 ival >>= PyLong_SHIFT;
1139 }
1140 }
1141 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001142}
1143
Mark Dickinson8d48b432011-10-23 20:47:14 +01001144/* Get a C long long int from a long int object or any object that has an
1145 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001146
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001147PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001148PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 PyLongObject *v;
1151 PY_LONG_LONG bytes;
1152 int one = 1;
1153 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (vv == NULL) {
1156 PyErr_BadInternalCall();
1157 return -1;
1158 }
1159 if (!PyLong_Check(vv)) {
1160 PyNumberMethods *nb;
1161 PyObject *io;
1162 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1163 nb->nb_int == NULL) {
1164 PyErr_SetString(PyExc_TypeError, "an integer is required");
1165 return -1;
1166 }
1167 io = (*nb->nb_int) (vv);
1168 if (io == NULL)
1169 return -1;
1170 if (PyLong_Check(io)) {
1171 bytes = PyLong_AsLongLong(io);
1172 Py_DECREF(io);
1173 return bytes;
1174 }
1175 Py_DECREF(io);
1176 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1177 return -1;
1178 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 v = (PyLongObject*)vv;
1181 switch(Py_SIZE(v)) {
1182 case -1: return -(sdigit)v->ob_digit[0];
1183 case 0: return 0;
1184 case 1: return v->ob_digit[0];
1185 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001186 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1187 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1190 if (res < 0)
1191 return (PY_LONG_LONG)-1;
1192 else
1193 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194}
1195
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001196/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001197 Return -1 and set an error if overflow occurs. */
1198
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001199unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001200PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyLongObject *v;
1203 unsigned PY_LONG_LONG bytes;
1204 int one = 1;
1205 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001206
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001207 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyErr_BadInternalCall();
1209 return (unsigned PY_LONG_LONG)-1;
1210 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001211 if (!PyLong_Check(vv)) {
1212 PyErr_SetString(PyExc_TypeError, "an integer is required");
1213 return (unsigned PY_LONG_LONG)-1;
1214 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 v = (PyLongObject*)vv;
1217 switch(Py_SIZE(v)) {
1218 case 0: return 0;
1219 case 1: return v->ob_digit[0];
1220 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001221
Mark Dickinson22b20182010-05-10 21:27:53 +00001222 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1223 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1226 if (res < 0)
1227 return (unsigned PY_LONG_LONG)res;
1228 else
1229 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001230}
Tim Petersd1a7da62001-06-13 00:35:57 +00001231
Thomas Hellera4ea6032003-04-17 18:55:45 +00001232/* Get a C unsigned long int from a long int object, ignoring the high bits.
1233 Returns -1 and sets an error condition if an error occurs. */
1234
Guido van Rossumddefaf32007-01-14 03:31:43 +00001235static unsigned PY_LONG_LONG
1236_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 register PyLongObject *v;
1239 unsigned PY_LONG_LONG x;
1240 Py_ssize_t i;
1241 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (vv == NULL || !PyLong_Check(vv)) {
1244 PyErr_BadInternalCall();
1245 return (unsigned long) -1;
1246 }
1247 v = (PyLongObject *)vv;
1248 switch(Py_SIZE(v)) {
1249 case 0: return 0;
1250 case 1: return v->ob_digit[0];
1251 }
1252 i = Py_SIZE(v);
1253 sign = 1;
1254 x = 0;
1255 if (i < 0) {
1256 sign = -1;
1257 i = -i;
1258 }
1259 while (--i >= 0) {
1260 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1261 }
1262 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001263}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001264
1265unsigned PY_LONG_LONG
1266PyLong_AsUnsignedLongLongMask(register PyObject *op)
1267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 PyNumberMethods *nb;
1269 PyLongObject *lo;
1270 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (op && PyLong_Check(op))
1273 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1276 nb->nb_int == NULL) {
1277 PyErr_SetString(PyExc_TypeError, "an integer is required");
1278 return (unsigned PY_LONG_LONG)-1;
1279 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 lo = (PyLongObject*) (*nb->nb_int) (op);
1282 if (lo == NULL)
1283 return (unsigned PY_LONG_LONG)-1;
1284 if (PyLong_Check(lo)) {
1285 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1286 Py_DECREF(lo);
1287 if (PyErr_Occurred())
1288 return (unsigned PY_LONG_LONG)-1;
1289 return val;
1290 }
1291 else
1292 {
1293 Py_DECREF(lo);
1294 PyErr_SetString(PyExc_TypeError,
1295 "nb_int should return int object");
1296 return (unsigned PY_LONG_LONG)-1;
1297 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001298}
Tim Petersd1a7da62001-06-13 00:35:57 +00001299#undef IS_LITTLE_ENDIAN
1300
Mark Dickinson8d48b432011-10-23 20:47:14 +01001301/* Get a C long long int from a long int object or any object that has an
1302 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001303
Mark Dickinson8d48b432011-10-23 20:47:14 +01001304 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1305 the result. Otherwise *overflow is 0.
1306
1307 For other errors (e.g., TypeError), return -1 and set an error condition.
1308 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001309*/
1310
1311PY_LONG_LONG
1312PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 /* This version by Tim Peters */
1315 register PyLongObject *v;
1316 unsigned PY_LONG_LONG x, prev;
1317 PY_LONG_LONG res;
1318 Py_ssize_t i;
1319 int sign;
1320 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 *overflow = 0;
1323 if (vv == NULL) {
1324 PyErr_BadInternalCall();
1325 return -1;
1326 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (!PyLong_Check(vv)) {
1329 PyNumberMethods *nb;
1330 nb = vv->ob_type->tp_as_number;
1331 if (nb == NULL || nb->nb_int == NULL) {
1332 PyErr_SetString(PyExc_TypeError,
1333 "an integer is required");
1334 return -1;
1335 }
1336 vv = (*nb->nb_int) (vv);
1337 if (vv == NULL)
1338 return -1;
1339 do_decref = 1;
1340 if (!PyLong_Check(vv)) {
1341 Py_DECREF(vv);
1342 PyErr_SetString(PyExc_TypeError,
1343 "nb_int should return int object");
1344 return -1;
1345 }
1346 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 res = -1;
1349 v = (PyLongObject *)vv;
1350 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 switch (i) {
1353 case -1:
1354 res = -(sdigit)v->ob_digit[0];
1355 break;
1356 case 0:
1357 res = 0;
1358 break;
1359 case 1:
1360 res = v->ob_digit[0];
1361 break;
1362 default:
1363 sign = 1;
1364 x = 0;
1365 if (i < 0) {
1366 sign = -1;
1367 i = -(i);
1368 }
1369 while (--i >= 0) {
1370 prev = x;
1371 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1372 if ((x >> PyLong_SHIFT) != prev) {
1373 *overflow = sign;
1374 goto exit;
1375 }
1376 }
1377 /* Haven't lost any bits, but casting to long requires extra
1378 * care (see comment above).
1379 */
1380 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1381 res = (PY_LONG_LONG)x * sign;
1382 }
1383 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1384 res = PY_LLONG_MIN;
1385 }
1386 else {
1387 *overflow = sign;
1388 /* res is already set to -1 */
1389 }
1390 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001391 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (do_decref) {
1393 Py_DECREF(vv);
1394 }
1395 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001396}
1397
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001398#endif /* HAVE_LONG_LONG */
1399
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001400#define CHECK_BINOP(v,w) \
1401 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001402 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1403 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001404 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001405
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001406/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1407 2**k if d is nonzero, else 0. */
1408
1409static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1411 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001412};
1413
1414static int
1415bits_in_digit(digit d)
1416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 int d_bits = 0;
1418 while (d >= 32) {
1419 d_bits += 6;
1420 d >>= 6;
1421 }
1422 d_bits += (int)BitLengthTable[d];
1423 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001424}
1425
Tim Peters877a2122002-08-12 05:09:36 +00001426/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1427 * is modified in place, by adding y to it. Carries are propagated as far as
1428 * x[m-1], and the remaining carry (0 or 1) is returned.
1429 */
1430static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001431v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 Py_ssize_t i;
1434 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 assert(m >= n);
1437 for (i = 0; i < n; ++i) {
1438 carry += x[i] + y[i];
1439 x[i] = carry & PyLong_MASK;
1440 carry >>= PyLong_SHIFT;
1441 assert((carry & 1) == carry);
1442 }
1443 for (; carry && i < m; ++i) {
1444 carry += x[i];
1445 x[i] = carry & PyLong_MASK;
1446 carry >>= PyLong_SHIFT;
1447 assert((carry & 1) == carry);
1448 }
1449 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001450}
1451
1452/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1453 * is modified in place, by subtracting y from it. Borrows are propagated as
1454 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1455 */
1456static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001457v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 Py_ssize_t i;
1460 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 assert(m >= n);
1463 for (i = 0; i < n; ++i) {
1464 borrow = x[i] - y[i] - borrow;
1465 x[i] = borrow & PyLong_MASK;
1466 borrow >>= PyLong_SHIFT;
1467 borrow &= 1; /* keep only 1 sign bit */
1468 }
1469 for (; borrow && i < m; ++i) {
1470 borrow = x[i] - borrow;
1471 x[i] = borrow & PyLong_MASK;
1472 borrow >>= PyLong_SHIFT;
1473 borrow &= 1;
1474 }
1475 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001476}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001477
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001478/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1479 * result in z[0:m], and return the d bits shifted out of the top.
1480 */
1481static digit
1482v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 Py_ssize_t i;
1485 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 assert(0 <= d && d < PyLong_SHIFT);
1488 for (i=0; i < m; i++) {
1489 twodigits acc = (twodigits)a[i] << d | carry;
1490 z[i] = (digit)acc & PyLong_MASK;
1491 carry = (digit)(acc >> PyLong_SHIFT);
1492 }
1493 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001494}
1495
1496/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1497 * result in z[0:m], and return the d bits shifted out of the bottom.
1498 */
1499static digit
1500v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 Py_ssize_t i;
1503 digit carry = 0;
1504 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 assert(0 <= d && d < PyLong_SHIFT);
1507 for (i=m; i-- > 0;) {
1508 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1509 carry = (digit)acc & mask;
1510 z[i] = (digit)(acc >> d);
1511 }
1512 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001513}
1514
Tim Peters212e6142001-07-14 12:23:19 +00001515/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1516 in pout, and returning the remainder. pin and pout point at the LSD.
1517 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001518 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001519 immutable. */
1520
1521static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001522inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 assert(n > 0 && n <= PyLong_MASK);
1527 pin += size;
1528 pout += size;
1529 while (--size >= 0) {
1530 digit hi;
1531 rem = (rem << PyLong_SHIFT) | *--pin;
1532 *--pout = hi = (digit)(rem / n);
1533 rem -= (twodigits)hi * n;
1534 }
1535 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001536}
1537
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001538/* Divide a long integer by a digit, returning both the quotient
1539 (as function result) and the remainder (through *prem).
1540 The sign of a is ignored; n should not be zero. */
1541
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001542static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001543divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 const Py_ssize_t size = ABS(Py_SIZE(a));
1546 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 assert(n > 0 && n <= PyLong_MASK);
1549 z = _PyLong_New(size);
1550 if (z == NULL)
1551 return NULL;
1552 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1553 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001554}
1555
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001556/* Convert a long integer to a base 10 string. Returns a new non-shared
1557 string. (Return value is non-shared so that callers can modify the
1558 returned value if necessary.) */
1559
Victor Stinnerd3f08822012-05-29 12:57:52 +02001560static int
1561long_to_decimal_string_internal(PyObject *aa,
1562 PyObject **p_output,
1563 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyLongObject *scratch, *a;
1566 PyObject *str;
1567 Py_ssize_t size, strlen, size_a, i, j;
1568 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001570 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 a = (PyLongObject *)aa;
1573 if (a == NULL || !PyLong_Check(a)) {
1574 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001575 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 }
1577 size_a = ABS(Py_SIZE(a));
1578 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 /* quick and dirty upper bound for the number of digits
1581 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 But log2(a) < size_a * PyLong_SHIFT, and
1586 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1587 > 3 * _PyLong_DECIMAL_SHIFT
1588 */
1589 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1590 PyErr_SetString(PyExc_OverflowError,
1591 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001592 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 }
1594 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1595 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1596 scratch = _PyLong_New(size);
1597 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001598 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 /* convert array of base _PyLong_BASE digits in pin to an array of
1601 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1602 Volume 2 (3rd edn), section 4.4, Method 1b). */
1603 pin = a->ob_digit;
1604 pout = scratch->ob_digit;
1605 size = 0;
1606 for (i = size_a; --i >= 0; ) {
1607 digit hi = pin[i];
1608 for (j = 0; j < size; j++) {
1609 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1610 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1611 pout[j] = (digit)(z - (twodigits)hi *
1612 _PyLong_DECIMAL_BASE);
1613 }
1614 while (hi) {
1615 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1616 hi /= _PyLong_DECIMAL_BASE;
1617 }
1618 /* check for keyboard interrupt */
1619 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001620 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001621 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001622 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 }
1624 /* pout should have at least one digit, so that the case when a = 0
1625 works correctly */
1626 if (size == 0)
1627 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 /* calculate exact length of output string, and allocate */
1630 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1631 tenpow = 10;
1632 rem = pout[size-1];
1633 while (rem >= tenpow) {
1634 tenpow *= 10;
1635 strlen++;
1636 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001637 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001638 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1639 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001640 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001641 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001642 kind = writer->kind;
1643 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001645 else {
1646 str = PyUnicode_New(strlen, '9');
1647 if (str == NULL) {
1648 Py_DECREF(scratch);
1649 return -1;
1650 }
1651 kind = PyUnicode_KIND(str);
1652 }
1653
1654#define WRITE_DIGITS(TYPE) \
1655 do { \
1656 if (writer) \
1657 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1658 else \
1659 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1660 \
1661 *p = '\0'; \
1662 /* pout[0] through pout[size-2] contribute exactly \
1663 _PyLong_DECIMAL_SHIFT digits each */ \
1664 for (i=0; i < size - 1; i++) { \
1665 rem = pout[i]; \
1666 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1667 *--p = '0' + rem % 10; \
1668 rem /= 10; \
1669 } \
1670 } \
1671 /* pout[size-1]: always produce at least one decimal digit */ \
1672 rem = pout[i]; \
1673 do { \
1674 *--p = '0' + rem % 10; \
1675 rem /= 10; \
1676 } while (rem != 0); \
1677 \
1678 /* and sign */ \
1679 if (negative) \
1680 *--p = '-'; \
1681 \
1682 /* check we've counted correctly */ \
1683 if (writer) \
1684 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1685 else \
1686 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1687 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001690 if (kind == PyUnicode_1BYTE_KIND) {
1691 Py_UCS1 *p;
1692 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001694 else if (kind == PyUnicode_2BYTE_KIND) {
1695 Py_UCS2 *p;
1696 WRITE_DIGITS(Py_UCS2);
1697 }
1698 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001699 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001700 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001701 WRITE_DIGITS(Py_UCS4);
1702 }
1703#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001706 if (writer) {
1707 writer->pos += strlen;
1708 }
1709 else {
1710 assert(_PyUnicode_CheckConsistency(str, 1));
1711 *p_output = (PyObject *)str;
1712 }
1713 return 0;
1714}
1715
1716static PyObject *
1717long_to_decimal_string(PyObject *aa)
1718{
1719 PyObject *v;
1720 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1721 return NULL;
1722 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001723}
1724
Mark Dickinsoncd068122009-09-18 14:53:08 +00001725/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001726 which should be one of 2, 8 or 16. Return a string object.
1727 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1728 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001729
Victor Stinnerd3f08822012-05-29 12:57:52 +02001730static int
1731long_format_binary(PyObject *aa, int base, int alternate,
1732 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001735 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001736 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001738 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001739 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001741
Victor Stinnerd3f08822012-05-29 12:57:52 +02001742 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (a == NULL || !PyLong_Check(a)) {
1744 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001745 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 }
1747 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001748 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 /* Compute a rough upper bound for the length of the string */
1751 switch (base) {
1752 case 16:
1753 bits = 4;
1754 break;
1755 case 8:
1756 bits = 3;
1757 break;
1758 case 2:
1759 bits = 1;
1760 break;
1761 default:
1762 assert(0); /* shouldn't ever get here */
1763 bits = 0; /* to silence gcc warning */
1764 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001765
Mark Dickinsone2846542012-04-20 21:21:24 +01001766 /* Compute exact length 'sz' of output string. */
1767 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001768 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001769 }
1770 else {
1771 Py_ssize_t size_a_in_bits;
1772 /* Ensure overflow doesn't occur during computation of sz. */
1773 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1774 PyErr_SetString(PyExc_OverflowError,
1775 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001776 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001777 }
1778 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1779 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001780 /* Allow 1 character for a '-' sign. */
1781 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1782 }
1783 if (alternate) {
1784 /* 2 characters for prefix */
1785 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001786 }
1787
Victor Stinnerd3f08822012-05-29 12:57:52 +02001788 if (writer) {
1789 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1790 return -1;
1791 kind = writer->kind;
1792 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 }
1794 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001795 v = PyUnicode_New(sz, 'x');
1796 if (v == NULL)
1797 return -1;
1798 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001800
Victor Stinnerd3f08822012-05-29 12:57:52 +02001801#define WRITE_DIGITS(TYPE) \
1802 do { \
1803 if (writer) \
1804 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1805 else \
1806 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1807 \
1808 if (size_a == 0) { \
1809 *--p = '0'; \
1810 } \
1811 else { \
1812 /* JRH: special case for power-of-2 bases */ \
1813 twodigits accum = 0; \
1814 int accumbits = 0; /* # of bits in accum */ \
1815 Py_ssize_t i; \
1816 for (i = 0; i < size_a; ++i) { \
1817 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1818 accumbits += PyLong_SHIFT; \
1819 assert(accumbits >= bits); \
1820 do { \
1821 char cdigit; \
1822 cdigit = (char)(accum & (base - 1)); \
1823 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1824 *--p = cdigit; \
1825 accumbits -= bits; \
1826 accum >>= bits; \
1827 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1828 } \
1829 } \
1830 \
1831 if (alternate) { \
1832 if (base == 16) \
1833 *--p = 'x'; \
1834 else if (base == 8) \
1835 *--p = 'o'; \
1836 else /* (base == 2) */ \
1837 *--p = 'b'; \
1838 *--p = '0'; \
1839 } \
1840 if (negative) \
1841 *--p = '-'; \
1842 if (writer) \
1843 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1844 else \
1845 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1846 } while (0)
1847
1848 if (kind == PyUnicode_1BYTE_KIND) {
1849 Py_UCS1 *p;
1850 WRITE_DIGITS(Py_UCS1);
1851 }
1852 else if (kind == PyUnicode_2BYTE_KIND) {
1853 Py_UCS2 *p;
1854 WRITE_DIGITS(Py_UCS2);
1855 }
1856 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001857 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001858 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001859 WRITE_DIGITS(Py_UCS4);
1860 }
1861#undef WRITE_DIGITS
1862
1863 if (writer) {
1864 writer->pos += sz;
1865 }
1866 else {
1867 assert(_PyUnicode_CheckConsistency(v, 1));
1868 *p_output = v;
1869 }
1870 return 0;
1871}
1872
1873PyObject *
1874_PyLong_Format(PyObject *obj, int base)
1875{
1876 PyObject *str;
1877 int err;
1878 if (base == 10)
1879 err = long_to_decimal_string_internal(obj, &str, NULL);
1880 else
1881 err = long_format_binary(obj, base, 1, &str, NULL);
1882 if (err == -1)
1883 return NULL;
1884 return str;
1885}
1886
1887int
1888_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1889 PyObject *obj,
1890 int base, int alternate)
1891{
1892 if (base == 10)
1893 return long_to_decimal_string_internal(obj, NULL, writer);
1894 else
1895 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001896}
1897
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898/* Table of digit values for 8-bit string -> integer conversion.
1899 * '0' maps to 0, ..., '9' maps to 9.
1900 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1901 * All other indices map to 37.
1902 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001903 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001905unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1907 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1908 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1909 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1910 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1911 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1912 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1913 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1914 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1915 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1916 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1917 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1918 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1919 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1920 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1921 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922};
1923
1924/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001925 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1926 * non-digit (which may be *str!). A normalized long is returned.
1927 * The point to this routine is that it takes time linear in the number of
1928 * string characters.
1929 */
1930static PyLongObject *
1931long_from_binary_base(char **str, int base)
1932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 char *p = *str;
1934 char *start = p;
1935 int bits_per_char;
1936 Py_ssize_t n;
1937 PyLongObject *z;
1938 twodigits accum;
1939 int bits_in_accum;
1940 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1943 n = base;
1944 for (bits_per_char = -1; n; ++bits_per_char)
1945 n >>= 1;
1946 /* n <- total # of bits needed, while setting p to end-of-string */
1947 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1948 ++p;
1949 *str = p;
1950 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1951 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1952 if (n / bits_per_char < p - start) {
1953 PyErr_SetString(PyExc_ValueError,
1954 "int string too large to convert");
1955 return NULL;
1956 }
1957 n = n / PyLong_SHIFT;
1958 z = _PyLong_New(n);
1959 if (z == NULL)
1960 return NULL;
1961 /* Read string from right, and fill in long from left; i.e.,
1962 * from least to most significant in both.
1963 */
1964 accum = 0;
1965 bits_in_accum = 0;
1966 pdigit = z->ob_digit;
1967 while (--p >= start) {
1968 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1969 assert(k >= 0 && k < base);
1970 accum |= (twodigits)k << bits_in_accum;
1971 bits_in_accum += bits_per_char;
1972 if (bits_in_accum >= PyLong_SHIFT) {
1973 *pdigit++ = (digit)(accum & PyLong_MASK);
1974 assert(pdigit - z->ob_digit <= n);
1975 accum >>= PyLong_SHIFT;
1976 bits_in_accum -= PyLong_SHIFT;
1977 assert(bits_in_accum < PyLong_SHIFT);
1978 }
1979 }
1980 if (bits_in_accum) {
1981 assert(bits_in_accum <= PyLong_SHIFT);
1982 *pdigit++ = (digit)accum;
1983 assert(pdigit - z->ob_digit <= n);
1984 }
1985 while (pdigit - z->ob_digit < n)
1986 *pdigit++ = 0;
1987 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001988}
1989
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001990PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001991PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 int sign = 1, error_if_nonzero = 0;
1994 char *start, *orig_str = str;
1995 PyLongObject *z = NULL;
1996 PyObject *strobj;
1997 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 if ((base != 0 && base < 2) || base > 36) {
2000 PyErr_SetString(PyExc_ValueError,
2001 "int() arg 2 must be >= 2 and <= 36");
2002 return NULL;
2003 }
2004 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
2005 str++;
2006 if (*str == '+')
2007 ++str;
2008 else if (*str == '-') {
2009 ++str;
2010 sign = -1;
2011 }
2012 if (base == 0) {
2013 if (str[0] != '0')
2014 base = 10;
2015 else if (str[1] == 'x' || str[1] == 'X')
2016 base = 16;
2017 else if (str[1] == 'o' || str[1] == 'O')
2018 base = 8;
2019 else if (str[1] == 'b' || str[1] == 'B')
2020 base = 2;
2021 else {
2022 /* "old" (C-style) octal literal, now invalid.
2023 it might still be zero though */
2024 error_if_nonzero = 1;
2025 base = 10;
2026 }
2027 }
2028 if (str[0] == '0' &&
2029 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2030 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2031 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2032 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 start = str;
2035 if ((base & (base - 1)) == 0)
2036 z = long_from_binary_base(&str, base);
2037 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002038/***
2039Binary bases can be converted in time linear in the number of digits, because
2040Python's representation base is binary. Other bases (including decimal!) use
2041the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002042
Thomas Wouters477c8d52006-05-27 19:21:47 +00002043First some math: the largest integer that can be expressed in N base-B digits
2044is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2045case number of Python digits needed to hold it is the smallest integer n s.t.
2046
2047 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2048 BASE**n >= B**N [taking logs to base BASE]
2049 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2050
2051The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2052this quickly. A Python long with that much space is reserved near the start,
2053and the result is computed into it.
2054
2055The input string is actually treated as being in base base**i (i.e., i digits
2056are processed at a time), where two more static arrays hold:
2057
2058 convwidth_base[base] = the largest integer i such that base**i <= BASE
2059 convmultmax_base[base] = base ** convwidth_base[base]
2060
2061The first of these is the largest i such that i consecutive input digits
2062must fit in a single Python digit. The second is effectively the input
2063base we're really using.
2064
2065Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2066convmultmax_base[base], the result is "simply"
2067
2068 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2069
2070where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002071
2072Error analysis: as above, the number of Python digits `n` needed is worst-
2073case
2074
2075 n >= N * log(B)/log(BASE)
2076
2077where `N` is the number of input digits in base `B`. This is computed via
2078
2079 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2080
2081below. Two numeric concerns are how much space this can waste, and whether
2082the computed result can be too small. To be concrete, assume BASE = 2**15,
2083which is the default (and it's unlikely anyone changes that).
2084
2085Waste isn't a problem: provided the first input digit isn't 0, the difference
2086between the worst-case input with N digits and the smallest input with N
2087digits is about a factor of B, but B is small compared to BASE so at most
2088one allocated Python digit can remain unused on that count. If
2089N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2090and adding 1 returns a result 1 larger than necessary. However, that can't
2091happen: whenever B is a power of 2, long_from_binary_base() is called
2092instead, and it's impossible for B**i to be an integer power of 2**15 when
2093B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2094an exact integer when B is not a power of 2, since B**i has a prime factor
2095other than 2 in that case, but (2**15)**j's only prime factor is 2).
2096
2097The computed result can be too small if the true value of N*log(B)/log(BASE)
2098is a little bit larger than an exact integer, but due to roundoff errors (in
2099computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2100yields a numeric result a little less than that integer. Unfortunately, "how
2101close can a transcendental function get to an integer over some range?"
2102questions are generally theoretically intractable. Computer analysis via
2103continued fractions is practical: expand log(B)/log(BASE) via continued
2104fractions, giving a sequence i/j of "the best" rational approximations. Then
2105j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2106we can get very close to being in trouble, but very rarely. For example,
210776573 is a denominator in one of the continued-fraction approximations to
2108log(10)/log(2**15), and indeed:
2109
2110 >>> log(10)/log(2**15)*76573
2111 16958.000000654003
2112
2113is very close to an integer. If we were working with IEEE single-precision,
2114rounding errors could kill us. Finding worst cases in IEEE double-precision
2115requires better-than-double-precision log() functions, and Tim didn't bother.
2116Instead the code checks to see whether the allocated space is enough as each
2117new Python digit is added, and copies the whole thing to a larger long if not.
2118This should happen extremely rarely, and in fact I don't have a test case
2119that triggers it(!). Instead the code was tested by artificially allocating
2120just 1 digit at the start, so that the copying code was exercised for every
2121digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002122***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 register twodigits c; /* current input character */
2124 Py_ssize_t size_z;
2125 int i;
2126 int convwidth;
2127 twodigits convmultmax, convmult;
2128 digit *pz, *pzstop;
2129 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 static double log_base_BASE[37] = {0.0e0,};
2132 static int convwidth_base[37] = {0,};
2133 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 if (log_base_BASE[base] == 0.0) {
2136 twodigits convmax = base;
2137 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002138
Mark Dickinson22b20182010-05-10 21:27:53 +00002139 log_base_BASE[base] = (log((double)base) /
2140 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 for (;;) {
2142 twodigits next = convmax * base;
2143 if (next > PyLong_BASE)
2144 break;
2145 convmax = next;
2146 ++i;
2147 }
2148 convmultmax_base[base] = convmax;
2149 assert(i > 0);
2150 convwidth_base[base] = i;
2151 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 /* Find length of the string of numeric characters. */
2154 scan = str;
2155 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2156 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 /* Create a long object that can contain the largest possible
2159 * integer with this base and length. Note that there's no
2160 * need to initialize z->ob_digit -- no slot is read up before
2161 * being stored into.
2162 */
2163 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2164 /* Uncomment next line to test exceedingly rare copy code */
2165 /* size_z = 1; */
2166 assert(size_z > 0);
2167 z = _PyLong_New(size_z);
2168 if (z == NULL)
2169 return NULL;
2170 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 /* `convwidth` consecutive input digits are treated as a single
2173 * digit in base `convmultmax`.
2174 */
2175 convwidth = convwidth_base[base];
2176 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 /* Work ;-) */
2179 while (str < scan) {
2180 /* grab up to convwidth digits from the input string */
2181 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2182 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2183 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002184 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 assert(c < PyLong_BASE);
2186 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 convmult = convmultmax;
2189 /* Calculate the shift only if we couldn't get
2190 * convwidth digits.
2191 */
2192 if (i != convwidth) {
2193 convmult = base;
2194 for ( ; i > 1; --i)
2195 convmult *= base;
2196 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* Multiply z by convmult, and add c. */
2199 pz = z->ob_digit;
2200 pzstop = pz + Py_SIZE(z);
2201 for (; pz < pzstop; ++pz) {
2202 c += (twodigits)*pz * convmult;
2203 *pz = (digit)(c & PyLong_MASK);
2204 c >>= PyLong_SHIFT;
2205 }
2206 /* carry off the current end? */
2207 if (c) {
2208 assert(c < PyLong_BASE);
2209 if (Py_SIZE(z) < size_z) {
2210 *pz = (digit)c;
2211 ++Py_SIZE(z);
2212 }
2213 else {
2214 PyLongObject *tmp;
2215 /* Extremely rare. Get more space. */
2216 assert(Py_SIZE(z) == size_z);
2217 tmp = _PyLong_New(size_z + 1);
2218 if (tmp == NULL) {
2219 Py_DECREF(z);
2220 return NULL;
2221 }
2222 memcpy(tmp->ob_digit,
2223 z->ob_digit,
2224 sizeof(digit) * size_z);
2225 Py_DECREF(z);
2226 z = tmp;
2227 z->ob_digit[size_z] = (digit)c;
2228 ++size_z;
2229 }
2230 }
2231 }
2232 }
2233 if (z == NULL)
2234 return NULL;
2235 if (error_if_nonzero) {
2236 /* reset the base to 0, else the exception message
2237 doesn't make too much sense */
2238 base = 0;
2239 if (Py_SIZE(z) != 0)
2240 goto onError;
2241 /* there might still be other problems, therefore base
2242 remains zero here for the same reason */
2243 }
2244 if (str == start)
2245 goto onError;
2246 if (sign < 0)
2247 Py_SIZE(z) = -(Py_SIZE(z));
2248 while (*str && isspace(Py_CHARMASK(*str)))
2249 str++;
2250 if (*str != '\0')
2251 goto onError;
2252 if (pend)
2253 *pend = str;
2254 long_normalize(z);
2255 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002256
Mark Dickinson22b20182010-05-10 21:27:53 +00002257 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 Py_XDECREF(z);
2259 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2260 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2261 if (strobj == NULL)
2262 return NULL;
2263 PyErr_Format(PyExc_ValueError,
2264 "invalid literal for int() with base %d: %R",
2265 base, strobj);
2266 Py_DECREF(strobj);
2267 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002268}
2269
2270PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002271PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002272{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002273 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2274 if (unicode == NULL)
2275 return NULL;
2276 v = PyLong_FromUnicodeObject(unicode, base);
2277 Py_DECREF(unicode);
2278 return v;
2279}
2280
2281PyObject *
2282PyLong_FromUnicodeObject(PyObject *u, int base)
2283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002285 PyObject *asciidig;
2286 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002287 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002288
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002289 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002290 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002292 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002293 if (buffer == NULL) {
2294 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 return NULL;
2296 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002297 result = PyLong_FromString(buffer, &end, base);
2298 if (result != NULL && end != buffer + buflen) {
2299 PyErr_SetString(PyExc_ValueError,
2300 "null byte in argument for int()");
2301 Py_DECREF(result);
2302 result = NULL;
2303 }
2304 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002306}
2307
Tim Peters9f688bf2000-07-07 15:53:28 +00002308/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002309static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002311static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002312
2313/* Long division with remainder, top-level routine */
2314
Guido van Rossume32e0141992-01-19 16:31:05 +00002315static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002316long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2320 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 if (size_b == 0) {
2323 PyErr_SetString(PyExc_ZeroDivisionError,
2324 "integer division or modulo by zero");
2325 return -1;
2326 }
2327 if (size_a < size_b ||
2328 (size_a == size_b &&
2329 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2330 /* |a| < |b|. */
2331 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2332 if (*pdiv == NULL)
2333 return -1;
2334 Py_INCREF(a);
2335 *prem = (PyLongObject *) a;
2336 return 0;
2337 }
2338 if (size_b == 1) {
2339 digit rem = 0;
2340 z = divrem1(a, b->ob_digit[0], &rem);
2341 if (z == NULL)
2342 return -1;
2343 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2344 if (*prem == NULL) {
2345 Py_DECREF(z);
2346 return -1;
2347 }
2348 }
2349 else {
2350 z = x_divrem(a, b, prem);
2351 if (z == NULL)
2352 return -1;
2353 }
2354 /* Set the signs.
2355 The quotient z has the sign of a*b;
2356 the remainder r has the sign of a,
2357 so a = b*z + r. */
2358 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2359 NEGATE(z);
2360 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2361 NEGATE(*prem);
2362 *pdiv = maybe_small_long(z);
2363 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002364}
2365
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002366/* Unsigned long division with remainder -- the algorithm. The arguments v1
2367 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002368
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002369static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002370x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 PyLongObject *v, *w, *a;
2373 Py_ssize_t i, k, size_v, size_w;
2374 int d;
2375 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2376 twodigits vv;
2377 sdigit zhi;
2378 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2381 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2382 handle the special case when the initial estimate q for a quotient
2383 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2384 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* allocate space; w will also be used to hold the final remainder */
2387 size_v = ABS(Py_SIZE(v1));
2388 size_w = ABS(Py_SIZE(w1));
2389 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2390 v = _PyLong_New(size_v+1);
2391 if (v == NULL) {
2392 *prem = NULL;
2393 return NULL;
2394 }
2395 w = _PyLong_New(size_w);
2396 if (w == NULL) {
2397 Py_DECREF(v);
2398 *prem = NULL;
2399 return NULL;
2400 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2403 shift v1 left by the same amount. Results go into w and v. */
2404 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2405 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2406 assert(carry == 0);
2407 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2408 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2409 v->ob_digit[size_v] = carry;
2410 size_v++;
2411 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2414 at most (and usually exactly) k = size_v - size_w digits. */
2415 k = size_v - size_w;
2416 assert(k >= 0);
2417 a = _PyLong_New(k);
2418 if (a == NULL) {
2419 Py_DECREF(w);
2420 Py_DECREF(v);
2421 *prem = NULL;
2422 return NULL;
2423 }
2424 v0 = v->ob_digit;
2425 w0 = w->ob_digit;
2426 wm1 = w0[size_w-1];
2427 wm2 = w0[size_w-2];
2428 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2429 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2430 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002433 Py_DECREF(a);
2434 Py_DECREF(w);
2435 Py_DECREF(v);
2436 *prem = NULL;
2437 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002438 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 /* estimate quotient digit q; may overestimate by 1 (rare) */
2441 vtop = vk[size_w];
2442 assert(vtop <= wm1);
2443 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2444 q = (digit)(vv / wm1);
2445 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2446 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2447 | vk[size_w-2])) {
2448 --q;
2449 r += wm1;
2450 if (r >= PyLong_BASE)
2451 break;
2452 }
2453 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2456 zhi = 0;
2457 for (i = 0; i < size_w; ++i) {
2458 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2459 -PyLong_BASE * q <= z < PyLong_BASE */
2460 z = (sdigit)vk[i] + zhi -
2461 (stwodigits)q * (stwodigits)w0[i];
2462 vk[i] = (digit)z & PyLong_MASK;
2463 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002464 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 /* add w back if q was too large (this branch taken rarely) */
2468 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2469 if ((sdigit)vtop + zhi < 0) {
2470 carry = 0;
2471 for (i = 0; i < size_w; ++i) {
2472 carry += vk[i] + w0[i];
2473 vk[i] = carry & PyLong_MASK;
2474 carry >>= PyLong_SHIFT;
2475 }
2476 --q;
2477 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* store quotient digit */
2480 assert(q < PyLong_BASE);
2481 *--ak = q;
2482 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 /* unshift remainder; we reuse w to store the result */
2485 carry = v_rshift(w0, v0, size_w, d);
2486 assert(carry==0);
2487 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 *prem = long_normalize(w);
2490 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002491}
2492
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002493/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2494 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2495 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2496 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2497 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2498 -1.0. */
2499
2500/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2501#if DBL_MANT_DIG == 53
2502#define EXP2_DBL_MANT_DIG 9007199254740992.0
2503#else
2504#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2505#endif
2506
2507double
2508_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2511 /* See below for why x_digits is always large enough. */
2512 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2513 double dx;
2514 /* Correction term for round-half-to-even rounding. For a digit x,
2515 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2516 multiple of 4, rounding ties to a multiple of 8. */
2517 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 a_size = ABS(Py_SIZE(a));
2520 if (a_size == 0) {
2521 /* Special case for 0: significand 0.0, exponent 0. */
2522 *e = 0;
2523 return 0.0;
2524 }
2525 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2526 /* The following is an overflow-free version of the check
2527 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2528 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2529 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2530 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002531 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2535 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 Number of digits needed for result: write // for floor division.
2538 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2547 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2550 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2551 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 in both cases.
2558 */
2559 if (a_bits <= DBL_MANT_DIG + 2) {
2560 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2561 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2562 x_size = 0;
2563 while (x_size < shift_digits)
2564 x_digits[x_size++] = 0;
2565 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2566 (int)shift_bits);
2567 x_size += a_size;
2568 x_digits[x_size++] = rem;
2569 }
2570 else {
2571 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2572 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2573 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2574 a_size - shift_digits, (int)shift_bits);
2575 x_size = a_size - shift_digits;
2576 /* For correct rounding below, we need the least significant
2577 bit of x to be 'sticky' for this shift: if any of the bits
2578 shifted out was nonzero, we set the least significant bit
2579 of x. */
2580 if (rem)
2581 x_digits[0] |= 1;
2582 else
2583 while (shift_digits > 0)
2584 if (a->ob_digit[--shift_digits]) {
2585 x_digits[0] |= 1;
2586 break;
2587 }
2588 }
Victor Stinner63941882011-09-29 00:42:28 +02002589 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 /* Round, and convert to double. */
2592 x_digits[0] += half_even_correction[x_digits[0] & 7];
2593 dx = x_digits[--x_size];
2594 while (x_size > 0)
2595 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 /* Rescale; make correction if result is 1.0. */
2598 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2599 if (dx == 1.0) {
2600 if (a_bits == PY_SSIZE_T_MAX)
2601 goto overflow;
2602 dx = 0.5;
2603 a_bits += 1;
2604 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 *e = a_bits;
2607 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002608
2609 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 /* exponent > PY_SSIZE_T_MAX */
2611 PyErr_SetString(PyExc_OverflowError,
2612 "huge integer: number of bits overflows a Py_ssize_t");
2613 *e = 0;
2614 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002615}
2616
2617/* Get a C double from a long int object. Rounds to the nearest double,
2618 using the round-half-to-even rule in the case of a tie. */
2619
2620double
2621PyLong_AsDouble(PyObject *v)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 Py_ssize_t exponent;
2624 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002625
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002626 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 PyErr_BadInternalCall();
2628 return -1.0;
2629 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002630 if (!PyLong_Check(v)) {
2631 PyErr_SetString(PyExc_TypeError, "an integer is required");
2632 return -1.0;
2633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2635 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2636 PyErr_SetString(PyExc_OverflowError,
2637 "long int too large to convert to float");
2638 return -1.0;
2639 }
2640 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002641}
2642
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643/* Methods */
2644
2645static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002646long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002649}
2650
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002651static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002652long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 if (Py_SIZE(a) != Py_SIZE(b)) {
2657 sign = Py_SIZE(a) - Py_SIZE(b);
2658 }
2659 else {
2660 Py_ssize_t i = ABS(Py_SIZE(a));
2661 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2662 ;
2663 if (i < 0)
2664 sign = 0;
2665 else {
2666 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2667 if (Py_SIZE(a) < 0)
2668 sign = -sign;
2669 }
2670 }
2671 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002672}
2673
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002674#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002676
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002677static PyObject *
2678long_richcompare(PyObject *self, PyObject *other, int op)
2679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 int result;
2681 PyObject *v;
2682 CHECK_BINOP(self, other);
2683 if (self == other)
2684 result = 0;
2685 else
2686 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2687 /* Convert the return value to a Boolean */
2688 switch (op) {
2689 case Py_EQ:
2690 v = TEST_COND(result == 0);
2691 break;
2692 case Py_NE:
2693 v = TEST_COND(result != 0);
2694 break;
2695 case Py_LE:
2696 v = TEST_COND(result <= 0);
2697 break;
2698 case Py_GE:
2699 v = TEST_COND(result >= 0);
2700 break;
2701 case Py_LT:
2702 v = TEST_COND(result == -1);
2703 break;
2704 case Py_GT:
2705 v = TEST_COND(result == 1);
2706 break;
2707 default:
2708 PyErr_BadArgument();
2709 return NULL;
2710 }
2711 Py_INCREF(v);
2712 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002713}
2714
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002715static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002716long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002717{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002718 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 Py_ssize_t i;
2720 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 i = Py_SIZE(v);
2723 switch(i) {
2724 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2725 case 0: return 0;
2726 case 1: return v->ob_digit[0];
2727 }
2728 sign = 1;
2729 x = 0;
2730 if (i < 0) {
2731 sign = -1;
2732 i = -(i);
2733 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002735 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2736 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2737 _PyHASH_MODULUS.
2738
2739 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2740 amounts to a rotation of the bits of x. To see this, write
2741
2742 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2743
2744 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2745 PyLong_SHIFT bits of x (those that are shifted out of the
2746 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2747 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2748 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2749 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2750 congruent to y modulo _PyHASH_MODULUS. So
2751
2752 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2753
2754 The right-hand side is just the result of rotating the
2755 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2756 not all _PyHASH_BITS bits of x are 1s, the same is true
2757 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2758 the reduction of x*2**PyLong_SHIFT modulo
2759 _PyHASH_MODULUS. */
2760 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2761 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002763 if (x >= _PyHASH_MODULUS)
2764 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 }
2766 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002767 if (x == (Py_uhash_t)-1)
2768 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002769 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002770}
2771
2772
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002773/* Add the absolute values of two long integers. */
2774
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002775static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002776x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2779 PyLongObject *z;
2780 Py_ssize_t i;
2781 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 /* Ensure a is the larger of the two: */
2784 if (size_a < size_b) {
2785 { PyLongObject *temp = a; a = b; b = temp; }
2786 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002787 size_a = size_b;
2788 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 }
2790 z = _PyLong_New(size_a+1);
2791 if (z == NULL)
2792 return NULL;
2793 for (i = 0; i < size_b; ++i) {
2794 carry += a->ob_digit[i] + b->ob_digit[i];
2795 z->ob_digit[i] = carry & PyLong_MASK;
2796 carry >>= PyLong_SHIFT;
2797 }
2798 for (; i < size_a; ++i) {
2799 carry += a->ob_digit[i];
2800 z->ob_digit[i] = carry & PyLong_MASK;
2801 carry >>= PyLong_SHIFT;
2802 }
2803 z->ob_digit[i] = carry;
2804 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002805}
2806
2807/* Subtract the absolute values of two integers. */
2808
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002809static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002810x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2813 PyLongObject *z;
2814 Py_ssize_t i;
2815 int sign = 1;
2816 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 /* Ensure a is the larger of the two: */
2819 if (size_a < size_b) {
2820 sign = -1;
2821 { PyLongObject *temp = a; a = b; b = temp; }
2822 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002823 size_a = size_b;
2824 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 }
2826 else if (size_a == size_b) {
2827 /* Find highest digit where a and b differ: */
2828 i = size_a;
2829 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2830 ;
2831 if (i < 0)
2832 return (PyLongObject *)PyLong_FromLong(0);
2833 if (a->ob_digit[i] < b->ob_digit[i]) {
2834 sign = -1;
2835 { PyLongObject *temp = a; a = b; b = temp; }
2836 }
2837 size_a = size_b = i+1;
2838 }
2839 z = _PyLong_New(size_a);
2840 if (z == NULL)
2841 return NULL;
2842 for (i = 0; i < size_b; ++i) {
2843 /* The following assumes unsigned arithmetic
2844 works module 2**N for some N>PyLong_SHIFT. */
2845 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2846 z->ob_digit[i] = borrow & PyLong_MASK;
2847 borrow >>= PyLong_SHIFT;
2848 borrow &= 1; /* Keep only one sign bit */
2849 }
2850 for (; i < size_a; ++i) {
2851 borrow = a->ob_digit[i] - borrow;
2852 z->ob_digit[i] = borrow & PyLong_MASK;
2853 borrow >>= PyLong_SHIFT;
2854 borrow &= 1; /* Keep only one sign bit */
2855 }
2856 assert(borrow == 0);
2857 if (sign < 0)
2858 NEGATE(z);
2859 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002860}
2861
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002862static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002863long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2870 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2871 MEDIUM_VALUE(b));
2872 return result;
2873 }
2874 if (Py_SIZE(a) < 0) {
2875 if (Py_SIZE(b) < 0) {
2876 z = x_add(a, b);
2877 if (z != NULL && Py_SIZE(z) != 0)
2878 Py_SIZE(z) = -(Py_SIZE(z));
2879 }
2880 else
2881 z = x_sub(b, a);
2882 }
2883 else {
2884 if (Py_SIZE(b) < 0)
2885 z = x_sub(a, b);
2886 else
2887 z = x_add(a, b);
2888 }
2889 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002890}
2891
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002892static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002893long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2900 PyObject* r;
2901 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2902 return r;
2903 }
2904 if (Py_SIZE(a) < 0) {
2905 if (Py_SIZE(b) < 0)
2906 z = x_sub(a, b);
2907 else
2908 z = x_add(a, b);
2909 if (z != NULL && Py_SIZE(z) != 0)
2910 Py_SIZE(z) = -(Py_SIZE(z));
2911 }
2912 else {
2913 if (Py_SIZE(b) < 0)
2914 z = x_add(a, b);
2915 else
2916 z = x_sub(a, b);
2917 }
2918 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002919}
2920
Tim Peters5af4e6c2002-08-12 02:31:19 +00002921/* Grade school multiplication, ignoring the signs.
2922 * Returns the absolute value of the product, or NULL if error.
2923 */
2924static PyLongObject *
2925x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 PyLongObject *z;
2928 Py_ssize_t size_a = ABS(Py_SIZE(a));
2929 Py_ssize_t size_b = ABS(Py_SIZE(b));
2930 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 z = _PyLong_New(size_a + size_b);
2933 if (z == NULL)
2934 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2937 if (a == b) {
2938 /* Efficient squaring per HAC, Algorithm 14.16:
2939 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2940 * Gives slightly less than a 2x speedup when a == b,
2941 * via exploiting that each entry in the multiplication
2942 * pyramid appears twice (except for the size_a squares).
2943 */
2944 for (i = 0; i < size_a; ++i) {
2945 twodigits carry;
2946 twodigits f = a->ob_digit[i];
2947 digit *pz = z->ob_digit + (i << 1);
2948 digit *pa = a->ob_digit + i + 1;
2949 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002952 Py_DECREF(z);
2953 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002954 });
Tim Peters0973b992004-08-29 22:16:50 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 carry = *pz + f * f;
2957 *pz++ = (digit)(carry & PyLong_MASK);
2958 carry >>= PyLong_SHIFT;
2959 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 /* Now f is added in twice in each column of the
2962 * pyramid it appears. Same as adding f<<1 once.
2963 */
2964 f <<= 1;
2965 while (pa < paend) {
2966 carry += *pz + *pa++ * f;
2967 *pz++ = (digit)(carry & PyLong_MASK);
2968 carry >>= PyLong_SHIFT;
2969 assert(carry <= (PyLong_MASK << 1));
2970 }
2971 if (carry) {
2972 carry += *pz;
2973 *pz++ = (digit)(carry & PyLong_MASK);
2974 carry >>= PyLong_SHIFT;
2975 }
2976 if (carry)
2977 *pz += (digit)(carry & PyLong_MASK);
2978 assert((carry >> PyLong_SHIFT) == 0);
2979 }
2980 }
2981 else { /* a is not the same as b -- gradeschool long mult */
2982 for (i = 0; i < size_a; ++i) {
2983 twodigits carry = 0;
2984 twodigits f = a->ob_digit[i];
2985 digit *pz = z->ob_digit + i;
2986 digit *pb = b->ob_digit;
2987 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002990 Py_DECREF(z);
2991 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002992 });
Tim Peters0973b992004-08-29 22:16:50 +00002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 while (pb < pbend) {
2995 carry += *pz + *pb++ * f;
2996 *pz++ = (digit)(carry & PyLong_MASK);
2997 carry >>= PyLong_SHIFT;
2998 assert(carry <= PyLong_MASK);
2999 }
3000 if (carry)
3001 *pz += (digit)(carry & PyLong_MASK);
3002 assert((carry >> PyLong_SHIFT) == 0);
3003 }
3004 }
3005 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003006}
3007
3008/* A helper for Karatsuba multiplication (k_mul).
3009 Takes a long "n" and an integer "size" representing the place to
3010 split, and sets low and high such that abs(n) == (high << size) + low,
3011 viewing the shift as being by digits. The sign bit is ignored, and
3012 the return values are >= 0.
3013 Returns 0 on success, -1 on failure.
3014*/
3015static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003016kmul_split(PyLongObject *n,
3017 Py_ssize_t size,
3018 PyLongObject **high,
3019 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 PyLongObject *hi, *lo;
3022 Py_ssize_t size_lo, size_hi;
3023 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 size_lo = MIN(size_n, size);
3026 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 if ((hi = _PyLong_New(size_hi)) == NULL)
3029 return -1;
3030 if ((lo = _PyLong_New(size_lo)) == NULL) {
3031 Py_DECREF(hi);
3032 return -1;
3033 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3036 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 *high = long_normalize(hi);
3039 *low = long_normalize(lo);
3040 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003041}
3042
Tim Peters60004642002-08-12 22:01:34 +00003043static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3044
Tim Peters5af4e6c2002-08-12 02:31:19 +00003045/* Karatsuba multiplication. Ignores the input signs, and returns the
3046 * absolute value of the product (or NULL if error).
3047 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3048 */
3049static PyLongObject *
3050k_mul(PyLongObject *a, PyLongObject *b)
3051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 Py_ssize_t asize = ABS(Py_SIZE(a));
3053 Py_ssize_t bsize = ABS(Py_SIZE(b));
3054 PyLongObject *ah = NULL;
3055 PyLongObject *al = NULL;
3056 PyLongObject *bh = NULL;
3057 PyLongObject *bl = NULL;
3058 PyLongObject *ret = NULL;
3059 PyLongObject *t1, *t2, *t3;
3060 Py_ssize_t shift; /* the number of digits we split off */
3061 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3064 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3065 * Then the original product is
3066 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3067 * By picking X to be a power of 2, "*X" is just shifting, and it's
3068 * been reduced to 3 multiplies on numbers half the size.
3069 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 /* We want to split based on the larger number; fiddle so that b
3072 * is largest.
3073 */
3074 if (asize > bsize) {
3075 t1 = a;
3076 a = b;
3077 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 i = asize;
3080 asize = bsize;
3081 bsize = i;
3082 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 /* Use gradeschool math when either number is too small. */
3085 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3086 if (asize <= i) {
3087 if (asize == 0)
3088 return (PyLongObject *)PyLong_FromLong(0);
3089 else
3090 return x_mul(a, b);
3091 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 /* If a is small compared to b, splitting on b gives a degenerate
3094 * case with ah==0, and Karatsuba may be (even much) less efficient
3095 * than "grade school" then. However, we can still win, by viewing
3096 * b as a string of "big digits", each of width a->ob_size. That
3097 * leads to a sequence of balanced calls to k_mul.
3098 */
3099 if (2 * asize <= bsize)
3100 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 /* Split a & b into hi & lo pieces. */
3103 shift = bsize >> 1;
3104 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3105 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 if (a == b) {
3108 bh = ah;
3109 bl = al;
3110 Py_INCREF(bh);
3111 Py_INCREF(bl);
3112 }
3113 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 /* The plan:
3116 * 1. Allocate result space (asize + bsize digits: that's always
3117 * enough).
3118 * 2. Compute ah*bh, and copy into result at 2*shift.
3119 * 3. Compute al*bl, and copy into result at 0. Note that this
3120 * can't overlap with #2.
3121 * 4. Subtract al*bl from the result, starting at shift. This may
3122 * underflow (borrow out of the high digit), but we don't care:
3123 * we're effectively doing unsigned arithmetic mod
3124 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3125 * borrows and carries out of the high digit can be ignored.
3126 * 5. Subtract ah*bh from the result, starting at shift.
3127 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3128 * at shift.
3129 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 /* 1. Allocate result space. */
3132 ret = _PyLong_New(asize + bsize);
3133 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003134#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 /* Fill with trash, to catch reference to uninitialized digits. */
3136 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003137#endif
Tim Peters44121a62002-08-12 06:17:58 +00003138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3140 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3141 assert(Py_SIZE(t1) >= 0);
3142 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3143 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3144 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 /* Zero-out the digits higher than the ah*bh copy. */
3147 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3148 if (i)
3149 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3150 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 /* 3. t2 <- al*bl, and copy into the low digits. */
3153 if ((t2 = k_mul(al, bl)) == NULL) {
3154 Py_DECREF(t1);
3155 goto fail;
3156 }
3157 assert(Py_SIZE(t2) >= 0);
3158 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3159 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 /* Zero out remaining digits. */
3162 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3163 if (i)
3164 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3167 * because it's fresher in cache.
3168 */
3169 i = Py_SIZE(ret) - shift; /* # digits after shift */
3170 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3171 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3174 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3177 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3178 Py_DECREF(ah);
3179 Py_DECREF(al);
3180 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 if (a == b) {
3183 t2 = t1;
3184 Py_INCREF(t2);
3185 }
3186 else if ((t2 = x_add(bh, bl)) == NULL) {
3187 Py_DECREF(t1);
3188 goto fail;
3189 }
3190 Py_DECREF(bh);
3191 Py_DECREF(bl);
3192 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 t3 = k_mul(t1, t2);
3195 Py_DECREF(t1);
3196 Py_DECREF(t2);
3197 if (t3 == NULL) goto fail;
3198 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 /* Add t3. It's not obvious why we can't run out of room here.
3201 * See the (*) comment after this function.
3202 */
3203 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3204 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003207
Mark Dickinson22b20182010-05-10 21:27:53 +00003208 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 Py_XDECREF(ret);
3210 Py_XDECREF(ah);
3211 Py_XDECREF(al);
3212 Py_XDECREF(bh);
3213 Py_XDECREF(bl);
3214 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003215}
3216
Tim Petersd6974a52002-08-13 20:37:51 +00003217/* (*) Why adding t3 can't "run out of room" above.
3218
Tim Petersab86c2b2002-08-15 20:06:00 +00003219Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3220to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003221
Tim Petersab86c2b2002-08-15 20:06:00 +000032221. For any integer i, i = c(i/2) + f(i/2). In particular,
3223 bsize = c(bsize/2) + f(bsize/2).
32242. shift = f(bsize/2)
32253. asize <= bsize
32264. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3227 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003228
Tim Petersab86c2b2002-08-15 20:06:00 +00003229We allocated asize + bsize result digits, and add t3 into them at an offset
3230of shift. This leaves asize+bsize-shift allocated digit positions for t3
3231to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3232asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003233
Tim Petersab86c2b2002-08-15 20:06:00 +00003234bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3235at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003236
Tim Petersab86c2b2002-08-15 20:06:00 +00003237If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3238digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3239most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003240
Tim Petersab86c2b2002-08-15 20:06:00 +00003241The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003242
Tim Petersab86c2b2002-08-15 20:06:00 +00003243 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003244
Tim Petersab86c2b2002-08-15 20:06:00 +00003245and we have asize + c(bsize/2) available digit positions. We need to show
3246this is always enough. An instance of c(bsize/2) cancels out in both, so
3247the question reduces to whether asize digits is enough to hold
3248(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3249then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3250asize 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 +00003251digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003252asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003253c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3254is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3255bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003256
Tim Peters48d52c02002-08-14 17:07:32 +00003257Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3258clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3259ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003260*/
3261
Tim Peters60004642002-08-12 22:01:34 +00003262/* b has at least twice the digits of a, and a is big enough that Karatsuba
3263 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3264 * of slices, each with a->ob_size digits, and multiply the slices by a,
3265 * one at a time. This gives k_mul balanced inputs to work with, and is
3266 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003267 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003268 * single-width slice overlap between successive partial sums).
3269 */
3270static PyLongObject *
3271k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 const Py_ssize_t asize = ABS(Py_SIZE(a));
3274 Py_ssize_t bsize = ABS(Py_SIZE(b));
3275 Py_ssize_t nbdone; /* # of b digits already multiplied */
3276 PyLongObject *ret;
3277 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 assert(asize > KARATSUBA_CUTOFF);
3280 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 /* Allocate result space, and zero it out. */
3283 ret = _PyLong_New(asize + bsize);
3284 if (ret == NULL)
3285 return NULL;
3286 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 /* Successive slices of b are copied into bslice. */
3289 bslice = _PyLong_New(asize);
3290 if (bslice == NULL)
3291 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 nbdone = 0;
3294 while (bsize > 0) {
3295 PyLongObject *product;
3296 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 /* Multiply the next slice of b by a. */
3299 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3300 nbtouse * sizeof(digit));
3301 Py_SIZE(bslice) = nbtouse;
3302 product = k_mul(a, bslice);
3303 if (product == NULL)
3304 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 /* Add into result. */
3307 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3308 product->ob_digit, Py_SIZE(product));
3309 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 bsize -= nbtouse;
3312 nbdone += nbtouse;
3313 }
Tim Peters60004642002-08-12 22:01:34 +00003314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 Py_DECREF(bslice);
3316 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003317
Mark Dickinson22b20182010-05-10 21:27:53 +00003318 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 Py_DECREF(ret);
3320 Py_XDECREF(bslice);
3321 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003322}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003323
3324static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003325long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 /* fast path for single-digit multiplication */
3332 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3333 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003334#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003336#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 /* if we don't have long long then we're almost certainly
3338 using 15-bit digits, so v will fit in a long. In the
3339 unlikely event that we're using 30-bit digits on a platform
3340 without long long, a large v will just cause us to fall
3341 through to the general multiplication code below. */
3342 if (v >= LONG_MIN && v <= LONG_MAX)
3343 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003344#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 z = k_mul(a, b);
3348 /* Negate if exactly one of the inputs is negative. */
3349 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3350 NEGATE(z);
3351 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003352}
3353
Guido van Rossume32e0141992-01-19 16:31:05 +00003354/* The / and % operators are now defined in terms of divmod().
3355 The expression a mod b has the value a - b*floor(a/b).
3356 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003357 |a| by |b|, with the sign of a. This is also expressed
3358 as a - b*trunc(a/b), if trunc truncates towards zero.
3359 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 a b a rem b a mod b
3361 13 10 3 3
3362 -13 10 -3 7
3363 13 -10 3 -7
3364 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003365 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003366 have different signs. We then subtract one from the 'div'
3367 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003368
Tim Peters47e52ee2004-08-30 02:44:38 +00003369/* Compute
3370 * *pdiv, *pmod = divmod(v, w)
3371 * NULL can be passed for pdiv or pmod, in which case that part of
3372 * the result is simply thrown away. The caller owns a reference to
3373 * each of these it requests (does not pass NULL for).
3374 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003375static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003376l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 if (long_divrem(v, w, &div, &mod) < 0)
3382 return -1;
3383 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3384 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3385 PyLongObject *temp;
3386 PyLongObject *one;
3387 temp = (PyLongObject *) long_add(mod, w);
3388 Py_DECREF(mod);
3389 mod = temp;
3390 if (mod == NULL) {
3391 Py_DECREF(div);
3392 return -1;
3393 }
3394 one = (PyLongObject *) PyLong_FromLong(1L);
3395 if (one == NULL ||
3396 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3397 Py_DECREF(mod);
3398 Py_DECREF(div);
3399 Py_XDECREF(one);
3400 return -1;
3401 }
3402 Py_DECREF(one);
3403 Py_DECREF(div);
3404 div = temp;
3405 }
3406 if (pdiv != NULL)
3407 *pdiv = div;
3408 else
3409 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 if (pmod != NULL)
3412 *pmod = mod;
3413 else
3414 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003417}
3418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003419static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003420long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 CHECK_BINOP(a, b);
3425 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3426 div = NULL;
3427 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003428}
3429
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003430/* PyLong/PyLong -> float, with correctly rounded result. */
3431
3432#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3433#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3434
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003435static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003436long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 PyLongObject *a, *b, *x;
3439 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3440 digit mask, low;
3441 int inexact, negate, a_is_small, b_is_small;
3442 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 CHECK_BINOP(v, w);
3445 a = (PyLongObject *)v;
3446 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 /*
3449 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3452 1. choose a suitable integer 'shift'
3453 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3454 3. adjust x for correct rounding
3455 4. convert x to a double dx with the same value
3456 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3461 returns either 0.0 or -0.0, depending on the sign of b. For a and
3462 b both nonzero, ignore signs of a and b, and add the sign back in
3463 at the end. Now write a_bits and b_bits for the bit lengths of a
3464 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3465 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3470 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3471 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3472 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 1. The integer 'shift' is chosen so that x has the right number of
3477 bits for a double, plus two or three extra bits that will be used
3478 in the rounding decisions. Writing a_bits and b_bits for the
3479 number of significant bits in a and b respectively, a
3480 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 This is fine in the usual case, but if a/b is smaller than the
3485 smallest normal float then it can lead to double rounding on an
3486 IEEE 754 platform, giving incorrectly rounded results. So we
3487 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 2. The quantity x is computed by first shifting a (left -shift bits
3492 if shift <= 0, right shift bits if shift > 0) and then dividing by
3493 b. For both the shift and the division, we keep track of whether
3494 the result is inexact, in a flag 'inexact'; this information is
3495 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 With the choice of shift above, together with our assumption that
3498 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3499 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3502 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 For float representability, we need x/2**extra_bits <
3507 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3508 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 To round, we just modify the bottom digit of x in-place; this can
3513 end up giving a digit with value > PyLONG_MASK, but that's not a
3514 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 With the original choices for shift above, extra_bits will always
3517 be 2 or 3. Then rounding under the round-half-to-even rule, we
3518 round up iff the most significant of the extra bits is 1, and
3519 either: (a) the computation of x in step 2 had an inexact result,
3520 or (b) at least one other of the extra bits is 1, or (c) the least
3521 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 4. Conversion to a double is straightforward; all floating-point
3524 operations involved in the conversion are exact, so there's no
3525 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3528 The result will always be exactly representable as a double, except
3529 in the case that it overflows. To avoid dependence on the exact
3530 behaviour of ldexp on overflow, we check for overflow before
3531 applying ldexp. The result of ldexp is adjusted for sign before
3532 returning.
3533 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 /* Reduce to case where a and b are both positive. */
3536 a_size = ABS(Py_SIZE(a));
3537 b_size = ABS(Py_SIZE(b));
3538 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3539 if (b_size == 0) {
3540 PyErr_SetString(PyExc_ZeroDivisionError,
3541 "division by zero");
3542 goto error;
3543 }
3544 if (a_size == 0)
3545 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 /* Fast path for a and b small (exactly representable in a double).
3548 Relies on floating-point division being correctly rounded; results
3549 may be subject to double rounding on x86 machines that operate with
3550 the x87 FPU set to 64-bit precision. */
3551 a_is_small = a_size <= MANT_DIG_DIGITS ||
3552 (a_size == MANT_DIG_DIGITS+1 &&
3553 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3554 b_is_small = b_size <= MANT_DIG_DIGITS ||
3555 (b_size == MANT_DIG_DIGITS+1 &&
3556 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3557 if (a_is_small && b_is_small) {
3558 double da, db;
3559 da = a->ob_digit[--a_size];
3560 while (a_size > 0)
3561 da = da * PyLong_BASE + a->ob_digit[--a_size];
3562 db = b->ob_digit[--b_size];
3563 while (b_size > 0)
3564 db = db * PyLong_BASE + b->ob_digit[--b_size];
3565 result = da / db;
3566 goto success;
3567 }
Tim Peterse2a60002001-09-04 06:17:36 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 /* Catch obvious cases of underflow and overflow */
3570 diff = a_size - b_size;
3571 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3572 /* Extreme overflow */
3573 goto overflow;
3574 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3575 /* Extreme underflow */
3576 goto underflow_or_zero;
3577 /* Next line is now safe from overflowing a Py_ssize_t */
3578 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3579 bits_in_digit(b->ob_digit[b_size - 1]);
3580 /* Now diff = a_bits - b_bits. */
3581 if (diff > DBL_MAX_EXP)
3582 goto overflow;
3583 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3584 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 /* Choose value for shift; see comments for step 1 above. */
3587 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 /* x = abs(a * 2**-shift) */
3592 if (shift <= 0) {
3593 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3594 digit rem;
3595 /* x = a << -shift */
3596 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3597 /* In practice, it's probably impossible to end up
3598 here. Both a and b would have to be enormous,
3599 using close to SIZE_T_MAX bytes of memory each. */
3600 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003601 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 goto error;
3603 }
3604 x = _PyLong_New(a_size + shift_digits + 1);
3605 if (x == NULL)
3606 goto error;
3607 for (i = 0; i < shift_digits; i++)
3608 x->ob_digit[i] = 0;
3609 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3610 a_size, -shift % PyLong_SHIFT);
3611 x->ob_digit[a_size + shift_digits] = rem;
3612 }
3613 else {
3614 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3615 digit rem;
3616 /* x = a >> shift */
3617 assert(a_size >= shift_digits);
3618 x = _PyLong_New(a_size - shift_digits);
3619 if (x == NULL)
3620 goto error;
3621 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3622 a_size - shift_digits, shift % PyLong_SHIFT);
3623 /* set inexact if any of the bits shifted out is nonzero */
3624 if (rem)
3625 inexact = 1;
3626 while (!inexact && shift_digits > 0)
3627 if (a->ob_digit[--shift_digits])
3628 inexact = 1;
3629 }
3630 long_normalize(x);
3631 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3634 reference to x, so it's safe to modify it in-place. */
3635 if (b_size == 1) {
3636 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3637 b->ob_digit[0]);
3638 long_normalize(x);
3639 if (rem)
3640 inexact = 1;
3641 }
3642 else {
3643 PyLongObject *div, *rem;
3644 div = x_divrem(x, b, &rem);
3645 Py_DECREF(x);
3646 x = div;
3647 if (x == NULL)
3648 goto error;
3649 if (Py_SIZE(rem))
3650 inexact = 1;
3651 Py_DECREF(rem);
3652 }
3653 x_size = ABS(Py_SIZE(x));
3654 assert(x_size > 0); /* result of division is never zero */
3655 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 /* The number of extra bits that have to be rounded away. */
3658 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3659 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 /* Round by directly modifying the low digit of x. */
3662 mask = (digit)1 << (extra_bits - 1);
3663 low = x->ob_digit[0] | inexact;
3664 if (low & mask && low & (3*mask-1))
3665 low += mask;
3666 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 /* Convert x to a double dx; the conversion is exact. */
3669 dx = x->ob_digit[--x_size];
3670 while (x_size > 0)
3671 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3672 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 /* Check whether ldexp result will overflow a double. */
3675 if (shift + x_bits >= DBL_MAX_EXP &&
3676 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3677 goto overflow;
3678 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003679
3680 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003682
3683 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003685
3686 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 PyErr_SetString(PyExc_OverflowError,
3688 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003689 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003691}
3692
3693static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003694long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 CHECK_BINOP(a, b);
3699
3700 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3701 mod = NULL;
3702 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003703}
3704
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003705static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003706long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 PyLongObject *div, *mod;
3709 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3714 return NULL;
3715 }
3716 z = PyTuple_New(2);
3717 if (z != NULL) {
3718 PyTuple_SetItem(z, 0, (PyObject *) div);
3719 PyTuple_SetItem(z, 1, (PyObject *) mod);
3720 }
3721 else {
3722 Py_DECREF(div);
3723 Py_DECREF(mod);
3724 }
3725 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003726}
3727
Tim Peters47e52ee2004-08-30 02:44:38 +00003728/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003729static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003730long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3733 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 PyLongObject *z = NULL; /* accumulated result */
3736 Py_ssize_t i, j, k; /* counters */
3737 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 /* 5-ary values. If the exponent is large enough, table is
3740 * precomputed so that table[i] == a**i % c for i in range(32).
3741 */
3742 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3743 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 /* a, b, c = v, w, x */
3746 CHECK_BINOP(v, w);
3747 a = (PyLongObject*)v; Py_INCREF(a);
3748 b = (PyLongObject*)w; Py_INCREF(b);
3749 if (PyLong_Check(x)) {
3750 c = (PyLongObject *)x;
3751 Py_INCREF(x);
3752 }
3753 else if (x == Py_None)
3754 c = NULL;
3755 else {
3756 Py_DECREF(a);
3757 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003758 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 }
Tim Peters4c483c42001-09-05 06:24:58 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3762 if (c) {
3763 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003764 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 goto Error;
3766 }
3767 else {
3768 /* else return a float. This works because we know
3769 that this calls float_pow() which converts its
3770 arguments to double. */
3771 Py_DECREF(a);
3772 Py_DECREF(b);
3773 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3774 }
3775 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 if (c) {
3778 /* if modulus == 0:
3779 raise ValueError() */
3780 if (Py_SIZE(c) == 0) {
3781 PyErr_SetString(PyExc_ValueError,
3782 "pow() 3rd argument cannot be 0");
3783 goto Error;
3784 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 /* if modulus < 0:
3787 negativeOutput = True
3788 modulus = -modulus */
3789 if (Py_SIZE(c) < 0) {
3790 negativeOutput = 1;
3791 temp = (PyLongObject *)_PyLong_Copy(c);
3792 if (temp == NULL)
3793 goto Error;
3794 Py_DECREF(c);
3795 c = temp;
3796 temp = NULL;
3797 NEGATE(c);
3798 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 /* if modulus == 1:
3801 return 0 */
3802 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3803 z = (PyLongObject *)PyLong_FromLong(0L);
3804 goto Done;
3805 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 /* if base < 0:
3808 base = base % modulus
3809 Having the base positive just makes things easier. */
3810 if (Py_SIZE(a) < 0) {
3811 if (l_divmod(a, c, NULL, &temp) < 0)
3812 goto Error;
3813 Py_DECREF(a);
3814 a = temp;
3815 temp = NULL;
3816 }
3817 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 /* At this point a, b, and c are guaranteed non-negative UNLESS
3820 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 z = (PyLongObject *)PyLong_FromLong(1L);
3823 if (z == NULL)
3824 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 /* Perform a modular reduction, X = X % c, but leave X alone if c
3827 * is NULL.
3828 */
3829#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003830 do { \
3831 if (c != NULL) { \
3832 if (l_divmod(X, c, NULL, &temp) < 0) \
3833 goto Error; \
3834 Py_XDECREF(X); \
3835 X = temp; \
3836 temp = NULL; \
3837 } \
3838 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 /* Multiply two values, then reduce the result:
3841 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003842#define MULT(X, Y, result) \
3843 do { \
3844 temp = (PyLongObject *)long_mul(X, Y); \
3845 if (temp == NULL) \
3846 goto Error; \
3847 Py_XDECREF(result); \
3848 result = temp; \
3849 temp = NULL; \
3850 REDUCE(result); \
3851 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3854 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3855 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3856 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3857 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003860 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003862 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 }
3864 }
3865 }
3866 else {
3867 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3868 Py_INCREF(z); /* still holds 1L */
3869 table[0] = z;
3870 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003871 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3874 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3877 const int index = (bi >> j) & 0x1f;
3878 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003879 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003881 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 }
3883 }
3884 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 if (negativeOutput && (Py_SIZE(z) != 0)) {
3887 temp = (PyLongObject *)long_sub(z, c);
3888 if (temp == NULL)
3889 goto Error;
3890 Py_DECREF(z);
3891 z = temp;
3892 temp = NULL;
3893 }
3894 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003895
Mark Dickinson22b20182010-05-10 21:27:53 +00003896 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 if (z != NULL) {
3898 Py_DECREF(z);
3899 z = NULL;
3900 }
3901 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003902 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3904 for (i = 0; i < 32; ++i)
3905 Py_XDECREF(table[i]);
3906 }
3907 Py_DECREF(a);
3908 Py_DECREF(b);
3909 Py_XDECREF(c);
3910 Py_XDECREF(temp);
3911 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003912}
3913
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003914static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003915long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 /* Implement ~x as -(x+1) */
3918 PyLongObject *x;
3919 PyLongObject *w;
3920 if (ABS(Py_SIZE(v)) <=1)
3921 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3922 w = (PyLongObject *)PyLong_FromLong(1L);
3923 if (w == NULL)
3924 return NULL;
3925 x = (PyLongObject *) long_add(v, w);
3926 Py_DECREF(w);
3927 if (x == NULL)
3928 return NULL;
3929 Py_SIZE(x) = -(Py_SIZE(x));
3930 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003931}
3932
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003933static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003934long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 PyLongObject *z;
3937 if (ABS(Py_SIZE(v)) <= 1)
3938 return PyLong_FromLong(-MEDIUM_VALUE(v));
3939 z = (PyLongObject *)_PyLong_Copy(v);
3940 if (z != NULL)
3941 Py_SIZE(z) = -(Py_SIZE(v));
3942 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003943}
3944
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003945static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003946long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 if (Py_SIZE(v) < 0)
3949 return long_neg(v);
3950 else
3951 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003952}
3953
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003954static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003955long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003958}
3959
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003960static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003961long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 PyLongObject *z = NULL;
3964 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3965 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 if (Py_SIZE(a) < 0) {
3970 /* Right shifting negative numbers is harder */
3971 PyLongObject *a1, *a2;
3972 a1 = (PyLongObject *) long_invert(a);
3973 if (a1 == NULL)
3974 goto rshift_error;
3975 a2 = (PyLongObject *) long_rshift(a1, b);
3976 Py_DECREF(a1);
3977 if (a2 == NULL)
3978 goto rshift_error;
3979 z = (PyLongObject *) long_invert(a2);
3980 Py_DECREF(a2);
3981 }
3982 else {
3983 shiftby = PyLong_AsSsize_t((PyObject *)b);
3984 if (shiftby == -1L && PyErr_Occurred())
3985 goto rshift_error;
3986 if (shiftby < 0) {
3987 PyErr_SetString(PyExc_ValueError,
3988 "negative shift count");
3989 goto rshift_error;
3990 }
3991 wordshift = shiftby / PyLong_SHIFT;
3992 newsize = ABS(Py_SIZE(a)) - wordshift;
3993 if (newsize <= 0)
3994 return PyLong_FromLong(0);
3995 loshift = shiftby % PyLong_SHIFT;
3996 hishift = PyLong_SHIFT - loshift;
3997 lomask = ((digit)1 << hishift) - 1;
3998 himask = PyLong_MASK ^ lomask;
3999 z = _PyLong_New(newsize);
4000 if (z == NULL)
4001 goto rshift_error;
4002 if (Py_SIZE(a) < 0)
4003 Py_SIZE(z) = -(Py_SIZE(z));
4004 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4005 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4006 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004007 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 }
4009 z = long_normalize(z);
4010 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004011 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004013
Guido van Rossumc6913e71991-11-19 20:26:46 +00004014}
4015
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004016static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004017long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 /* This version due to Tim Peters */
4020 PyLongObject *a = (PyLongObject*)v;
4021 PyLongObject *b = (PyLongObject*)w;
4022 PyLongObject *z = NULL;
4023 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4024 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 shiftby = PyLong_AsSsize_t((PyObject *)b);
4029 if (shiftby == -1L && PyErr_Occurred())
4030 goto lshift_error;
4031 if (shiftby < 0) {
4032 PyErr_SetString(PyExc_ValueError, "negative shift count");
4033 goto lshift_error;
4034 }
4035 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4036 wordshift = shiftby / PyLong_SHIFT;
4037 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 oldsize = ABS(Py_SIZE(a));
4040 newsize = oldsize + wordshift;
4041 if (remshift)
4042 ++newsize;
4043 z = _PyLong_New(newsize);
4044 if (z == NULL)
4045 goto lshift_error;
4046 if (Py_SIZE(a) < 0)
4047 NEGATE(z);
4048 for (i = 0; i < wordshift; i++)
4049 z->ob_digit[i] = 0;
4050 accum = 0;
4051 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4052 accum |= (twodigits)a->ob_digit[j] << remshift;
4053 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4054 accum >>= PyLong_SHIFT;
4055 }
4056 if (remshift)
4057 z->ob_digit[newsize-1] = (digit)accum;
4058 else
4059 assert(!accum);
4060 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004061 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004063}
4064
Mark Dickinson27a87a22009-10-25 20:43:34 +00004065/* Compute two's complement of digit vector a[0:m], writing result to
4066 z[0:m]. The digit vector a need not be normalized, but should not
4067 be entirely zero. a and z may point to the same digit vector. */
4068
4069static void
4070v_complement(digit *z, digit *a, Py_ssize_t m)
4071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 Py_ssize_t i;
4073 digit carry = 1;
4074 for (i = 0; i < m; ++i) {
4075 carry += a[i] ^ PyLong_MASK;
4076 z[i] = carry & PyLong_MASK;
4077 carry >>= PyLong_SHIFT;
4078 }
4079 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004080}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004081
4082/* Bitwise and/xor/or operations */
4083
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004084static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004085long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004087 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 int nega, negb, negz;
4090 Py_ssize_t size_a, size_b, size_z, i;
4091 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 /* Bitwise operations for negative numbers operate as though
4094 on a two's complement representation. So convert arguments
4095 from sign-magnitude to two's complement, and convert the
4096 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 /* If a is negative, replace it by its two's complement. */
4099 size_a = ABS(Py_SIZE(a));
4100 nega = Py_SIZE(a) < 0;
4101 if (nega) {
4102 z = _PyLong_New(size_a);
4103 if (z == NULL)
4104 return NULL;
4105 v_complement(z->ob_digit, a->ob_digit, size_a);
4106 a = z;
4107 }
4108 else
4109 /* Keep reference count consistent. */
4110 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 /* Same for b. */
4113 size_b = ABS(Py_SIZE(b));
4114 negb = Py_SIZE(b) < 0;
4115 if (negb) {
4116 z = _PyLong_New(size_b);
4117 if (z == NULL) {
4118 Py_DECREF(a);
4119 return NULL;
4120 }
4121 v_complement(z->ob_digit, b->ob_digit, size_b);
4122 b = z;
4123 }
4124 else
4125 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 /* Swap a and b if necessary to ensure size_a >= size_b. */
4128 if (size_a < size_b) {
4129 z = a; a = b; b = z;
4130 size_z = size_a; size_a = size_b; size_b = size_z;
4131 negz = nega; nega = negb; negb = negz;
4132 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 /* JRH: The original logic here was to allocate the result value (z)
4135 as the longer of the two operands. However, there are some cases
4136 where the result is guaranteed to be shorter than that: AND of two
4137 positives, OR of two negatives: use the shorter number. AND with
4138 mixed signs: use the positive number. OR with mixed signs: use the
4139 negative number.
4140 */
4141 switch (op) {
4142 case '^':
4143 negz = nega ^ negb;
4144 size_z = size_a;
4145 break;
4146 case '&':
4147 negz = nega & negb;
4148 size_z = negb ? size_a : size_b;
4149 break;
4150 case '|':
4151 negz = nega | negb;
4152 size_z = negb ? size_b : size_a;
4153 break;
4154 default:
4155 PyErr_BadArgument();
4156 return NULL;
4157 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 /* We allow an extra digit if z is negative, to make sure that
4160 the final two's complement of z doesn't overflow. */
4161 z = _PyLong_New(size_z + negz);
4162 if (z == NULL) {
4163 Py_DECREF(a);
4164 Py_DECREF(b);
4165 return NULL;
4166 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 /* Compute digits for overlap of a and b. */
4169 switch(op) {
4170 case '&':
4171 for (i = 0; i < size_b; ++i)
4172 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4173 break;
4174 case '|':
4175 for (i = 0; i < size_b; ++i)
4176 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4177 break;
4178 case '^':
4179 for (i = 0; i < size_b; ++i)
4180 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4181 break;
4182 default:
4183 PyErr_BadArgument();
4184 return NULL;
4185 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 /* Copy any remaining digits of a, inverting if necessary. */
4188 if (op == '^' && negb)
4189 for (; i < size_z; ++i)
4190 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4191 else if (i < size_z)
4192 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4193 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 /* Complement result if negative. */
4196 if (negz) {
4197 Py_SIZE(z) = -(Py_SIZE(z));
4198 z->ob_digit[size_z] = PyLong_MASK;
4199 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4200 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 Py_DECREF(a);
4203 Py_DECREF(b);
4204 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004205}
4206
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004207static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004208long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 PyObject *c;
4211 CHECK_BINOP(a, b);
4212 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4213 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004214}
4215
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004216static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004217long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 PyObject *c;
4220 CHECK_BINOP(a, b);
4221 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4222 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004223}
4224
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004225static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004226long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 PyObject *c;
4229 CHECK_BINOP(a, b);
4230 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4231 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004232}
4233
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004234static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004235long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 if (PyLong_CheckExact(v))
4238 Py_INCREF(v);
4239 else
4240 v = _PyLong_Copy((PyLongObject *)v);
4241 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004242}
4243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004244static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004245long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 double result;
4248 result = PyLong_AsDouble(v);
4249 if (result == -1.0 && PyErr_Occurred())
4250 return NULL;
4251 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004252}
4253
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004254static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004255long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004256
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257static PyObject *
4258long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4259{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004260 PyObject *obase = NULL, *x = NULL;
4261 long base;
4262 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 if (type != &PyLong_Type)
4266 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004267 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4268 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 return NULL;
4270 if (x == NULL)
4271 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004272 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004274
4275 base = PyLong_AsLongAndOverflow(obase, &overflow);
4276 if (base == -1 && PyErr_Occurred())
4277 return NULL;
4278 if (overflow || (base != 0 && base < 2) || base > 36) {
4279 PyErr_SetString(PyExc_ValueError,
4280 "int() arg 2 must be >= 2 and <= 36");
4281 return NULL;
4282 }
4283
4284 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004285 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4287 /* Since PyLong_FromString doesn't have a length parameter,
4288 * check here for possible NULs in the string. */
4289 char *string;
4290 Py_ssize_t size = Py_SIZE(x);
4291 if (PyByteArray_Check(x))
4292 string = PyByteArray_AS_STRING(x);
4293 else
4294 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004295 if (strlen(string) != (size_t)size || !size) {
4296 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 x is a bytes or buffer, *and* a base is given. */
4298 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004299 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004300 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 return NULL;
4302 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004303 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 }
4305 else {
4306 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004307 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 return NULL;
4309 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004310}
4311
Guido van Rossumbef14172001-08-29 15:47:46 +00004312/* Wimpy, slow approach to tp_new calls for subtypes of long:
4313 first create a regular long from whatever arguments we got,
4314 then allocate a subtype instance and initialize it from
4315 the regular long. The regular long is then thrown away.
4316*/
4317static PyObject *
4318long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 PyLongObject *tmp, *newobj;
4321 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 assert(PyType_IsSubtype(type, &PyLong_Type));
4324 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4325 if (tmp == NULL)
4326 return NULL;
4327 assert(PyLong_CheckExact(tmp));
4328 n = Py_SIZE(tmp);
4329 if (n < 0)
4330 n = -n;
4331 newobj = (PyLongObject *)type->tp_alloc(type, n);
4332 if (newobj == NULL) {
4333 Py_DECREF(tmp);
4334 return NULL;
4335 }
4336 assert(PyLong_Check(newobj));
4337 Py_SIZE(newobj) = Py_SIZE(tmp);
4338 for (i = 0; i < n; i++)
4339 newobj->ob_digit[i] = tmp->ob_digit[i];
4340 Py_DECREF(tmp);
4341 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004342}
4343
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004344static PyObject *
4345long_getnewargs(PyLongObject *v)
4346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004348}
4349
Guido van Rossumb43daf72007-08-01 18:08:08 +00004350static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004351long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004353}
4354
4355static PyObject *
4356long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004358}
4359
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004360static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004361long__format__(PyObject *self, PyObject *args)
4362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004364 _PyUnicodeWriter writer;
4365 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4368 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004369
4370 _PyUnicodeWriter_Init(&writer, 0);
4371 ret = _PyLong_FormatAdvancedWriter(
4372 &writer,
4373 self,
4374 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4375 if (ret == -1) {
4376 _PyUnicodeWriter_Dealloc(&writer);
4377 return NULL;
4378 }
4379 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004380}
4381
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004382/* Return a pair (q, r) such that a = b * q + r, and
4383 abs(r) <= abs(b)/2, with equality possible only if q is even.
4384 In other words, q == a / b, rounded to the nearest integer using
4385 round-half-to-even. */
4386
4387PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004388_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004389{
4390 PyLongObject *quo = NULL, *rem = NULL;
4391 PyObject *one = NULL, *twice_rem, *result, *temp;
4392 int cmp, quo_is_odd, quo_is_neg;
4393
4394 /* Equivalent Python code:
4395
4396 def divmod_near(a, b):
4397 q, r = divmod(a, b)
4398 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4399 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4400 # positive, 2 * r < b if b negative.
4401 greater_than_half = 2*r > b if b > 0 else 2*r < b
4402 exactly_half = 2*r == b
4403 if greater_than_half or exactly_half and q % 2 == 1:
4404 q += 1
4405 r -= b
4406 return q, r
4407
4408 */
4409 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4410 PyErr_SetString(PyExc_TypeError,
4411 "non-integer arguments in division");
4412 return NULL;
4413 }
4414
4415 /* Do a and b have different signs? If so, quotient is negative. */
4416 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4417
4418 one = PyLong_FromLong(1L);
4419 if (one == NULL)
4420 return NULL;
4421
4422 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4423 goto error;
4424
4425 /* compare twice the remainder with the divisor, to see
4426 if we need to adjust the quotient and remainder */
4427 twice_rem = long_lshift((PyObject *)rem, one);
4428 if (twice_rem == NULL)
4429 goto error;
4430 if (quo_is_neg) {
4431 temp = long_neg((PyLongObject*)twice_rem);
4432 Py_DECREF(twice_rem);
4433 twice_rem = temp;
4434 if (twice_rem == NULL)
4435 goto error;
4436 }
4437 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4438 Py_DECREF(twice_rem);
4439
4440 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4441 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4442 /* fix up quotient */
4443 if (quo_is_neg)
4444 temp = long_sub(quo, (PyLongObject *)one);
4445 else
4446 temp = long_add(quo, (PyLongObject *)one);
4447 Py_DECREF(quo);
4448 quo = (PyLongObject *)temp;
4449 if (quo == NULL)
4450 goto error;
4451 /* and remainder */
4452 if (quo_is_neg)
4453 temp = long_add(rem, (PyLongObject *)b);
4454 else
4455 temp = long_sub(rem, (PyLongObject *)b);
4456 Py_DECREF(rem);
4457 rem = (PyLongObject *)temp;
4458 if (rem == NULL)
4459 goto error;
4460 }
4461
4462 result = PyTuple_New(2);
4463 if (result == NULL)
4464 goto error;
4465
4466 /* PyTuple_SET_ITEM steals references */
4467 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4468 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4469 Py_DECREF(one);
4470 return result;
4471
4472 error:
4473 Py_XDECREF(quo);
4474 Py_XDECREF(rem);
4475 Py_XDECREF(one);
4476 return NULL;
4477}
4478
Eric Smith8c663262007-08-25 02:26:07 +00004479static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004480long_round(PyObject *self, PyObject *args)
4481{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004482 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004483
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004484 /* To round an integer m to the nearest 10**n (n positive), we make use of
4485 * the divmod_near operation, defined by:
4486 *
4487 * divmod_near(a, b) = (q, r)
4488 *
4489 * where q is the nearest integer to the quotient a / b (the
4490 * nearest even integer in the case of a tie) and r == a - q * b.
4491 * Hence q * b = a - r is the nearest multiple of b to a,
4492 * preferring even multiples in the case of a tie.
4493 *
4494 * So the nearest multiple of 10**n to m is:
4495 *
4496 * m - divmod_near(m, 10**n)[1].
4497 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4499 return NULL;
4500 if (o_ndigits == NULL)
4501 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004502
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004503 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 if (ndigits == NULL)
4505 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004506
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004507 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (Py_SIZE(ndigits) >= 0) {
4509 Py_DECREF(ndigits);
4510 return long_long(self);
4511 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004512
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004513 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4514 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004516 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004518 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004519
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004520 result = PyLong_FromLong(10L);
4521 if (result == NULL) {
4522 Py_DECREF(ndigits);
4523 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004525
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004526 temp = long_pow(result, ndigits, Py_None);
4527 Py_DECREF(ndigits);
4528 Py_DECREF(result);
4529 result = temp;
4530 if (result == NULL)
4531 return NULL;
4532
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004533 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004534 Py_DECREF(result);
4535 result = temp;
4536 if (result == NULL)
4537 return NULL;
4538
4539 temp = long_sub((PyLongObject *)self,
4540 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4541 Py_DECREF(result);
4542 result = temp;
4543
4544 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004545}
4546
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004547static PyObject *
4548long_sizeof(PyLongObject *v)
4549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4553 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004554}
4555
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004556static PyObject *
4557long_bit_length(PyLongObject *v)
4558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 PyLongObject *result, *x, *y;
4560 Py_ssize_t ndigits, msd_bits = 0;
4561 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 assert(v != NULL);
4564 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 ndigits = ABS(Py_SIZE(v));
4567 if (ndigits == 0)
4568 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 msd = v->ob_digit[ndigits-1];
4571 while (msd >= 32) {
4572 msd_bits += 6;
4573 msd >>= 6;
4574 }
4575 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4578 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 /* expression above may overflow; use Python integers instead */
4581 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4582 if (result == NULL)
4583 return NULL;
4584 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4585 if (x == NULL)
4586 goto error;
4587 y = (PyLongObject *)long_mul(result, x);
4588 Py_DECREF(x);
4589 if (y == NULL)
4590 goto error;
4591 Py_DECREF(result);
4592 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4595 if (x == NULL)
4596 goto error;
4597 y = (PyLongObject *)long_add(result, x);
4598 Py_DECREF(x);
4599 if (y == NULL)
4600 goto error;
4601 Py_DECREF(result);
4602 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004605
Mark Dickinson22b20182010-05-10 21:27:53 +00004606 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 Py_DECREF(result);
4608 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004609}
4610
4611PyDoc_STRVAR(long_bit_length_doc,
4612"int.bit_length() -> int\n\
4613\n\
4614Number of bits necessary to represent self in binary.\n\
4615>>> bin(37)\n\
4616'0b100101'\n\
4617>>> (37).bit_length()\n\
46186");
4619
Christian Heimes53876d92008-04-19 00:31:39 +00004620#if 0
4621static PyObject *
4622long_is_finite(PyObject *v)
4623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004625}
4626#endif
4627
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004628
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004629static PyObject *
4630long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 PyObject *byteorder_str;
4633 PyObject *is_signed_obj = NULL;
4634 Py_ssize_t length;
4635 int little_endian;
4636 int is_signed;
4637 PyObject *bytes;
4638 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4641 &length, &byteorder_str,
4642 &is_signed_obj))
4643 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 if (args != NULL && Py_SIZE(args) > 2) {
4646 PyErr_SetString(PyExc_TypeError,
4647 "'signed' is a keyword-only argument");
4648 return NULL;
4649 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4652 little_endian = 1;
4653 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4654 little_endian = 0;
4655 else {
4656 PyErr_SetString(PyExc_ValueError,
4657 "byteorder must be either 'little' or 'big'");
4658 return NULL;
4659 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 if (is_signed_obj != NULL) {
4662 int cmp = PyObject_IsTrue(is_signed_obj);
4663 if (cmp < 0)
4664 return NULL;
4665 is_signed = cmp ? 1 : 0;
4666 }
4667 else {
4668 /* If the signed argument was omitted, use False as the
4669 default. */
4670 is_signed = 0;
4671 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 if (length < 0) {
4674 PyErr_SetString(PyExc_ValueError,
4675 "length argument must be non-negative");
4676 return NULL;
4677 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 bytes = PyBytes_FromStringAndSize(NULL, length);
4680 if (bytes == NULL)
4681 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4684 length, little_endian, is_signed) < 0) {
4685 Py_DECREF(bytes);
4686 return NULL;
4687 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004690}
4691
Mark Dickinson078c2532010-01-30 18:06:17 +00004692PyDoc_STRVAR(long_to_bytes_doc,
4693"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004694\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004695Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004696\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004698raised if the integer is not representable with the given number of\n\
4699bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004700\n\
4701The byteorder argument determines the byte order used to represent the\n\
4702integer. If byteorder is 'big', the most significant byte is at the\n\
4703beginning of the byte array. If byteorder is 'little', the most\n\
4704significant byte is at the end of the byte array. To request the native\n\
4705byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4706\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004707The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004709is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004710
4711static PyObject *
4712long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 PyObject *byteorder_str;
4715 PyObject *is_signed_obj = NULL;
4716 int little_endian;
4717 int is_signed;
4718 PyObject *obj;
4719 PyObject *bytes;
4720 PyObject *long_obj;
4721 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4724 &obj, &byteorder_str,
4725 &is_signed_obj))
4726 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 if (args != NULL && Py_SIZE(args) > 2) {
4729 PyErr_SetString(PyExc_TypeError,
4730 "'signed' is a keyword-only argument");
4731 return NULL;
4732 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4735 little_endian = 1;
4736 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4737 little_endian = 0;
4738 else {
4739 PyErr_SetString(PyExc_ValueError,
4740 "byteorder must be either 'little' or 'big'");
4741 return NULL;
4742 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 if (is_signed_obj != NULL) {
4745 int cmp = PyObject_IsTrue(is_signed_obj);
4746 if (cmp < 0)
4747 return NULL;
4748 is_signed = cmp ? 1 : 0;
4749 }
4750 else {
4751 /* If the signed argument was omitted, use False as the
4752 default. */
4753 is_signed = 0;
4754 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 bytes = PyObject_Bytes(obj);
4757 if (bytes == NULL)
4758 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 long_obj = _PyLong_FromByteArray(
4761 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4762 little_endian, is_signed);
4763 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 /* If from_bytes() was used on subclass, allocate new subclass
4766 * instance, initialize it with decoded long value and return it.
4767 */
4768 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4769 PyLongObject *newobj;
4770 int i;
4771 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773 newobj = (PyLongObject *)type->tp_alloc(type, n);
4774 if (newobj == NULL) {
4775 Py_DECREF(long_obj);
4776 return NULL;
4777 }
4778 assert(PyLong_Check(newobj));
4779 Py_SIZE(newobj) = Py_SIZE(long_obj);
4780 for (i = 0; i < n; i++) {
4781 newobj->ob_digit[i] =
4782 ((PyLongObject *)long_obj)->ob_digit[i];
4783 }
4784 Py_DECREF(long_obj);
4785 return (PyObject *)newobj;
4786 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004789}
4790
Mark Dickinson078c2532010-01-30 18:06:17 +00004791PyDoc_STRVAR(long_from_bytes_doc,
4792"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4793\n\
4794Return the integer represented by the given array of bytes.\n\
4795\n\
4796The bytes argument must either support the buffer protocol or be an\n\
4797iterable object producing bytes. Bytes and bytearray are examples of\n\
4798built-in objects that support the buffer protocol.\n\
4799\n\
4800The byteorder argument determines the byte order used to represent the\n\
4801integer. If byteorder is 'big', the most significant byte is at the\n\
4802beginning of the byte array. If byteorder is 'little', the most\n\
4803significant byte is at the end of the byte array. To request the native\n\
4804byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4805\n\
4806The signed keyword-only argument indicates whether two's complement is\n\
4807used to represent the integer.");
4808
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004809static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4811 "Returns self, the complex conjugate of any int."},
4812 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4813 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004814#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4816 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004817#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 {"to_bytes", (PyCFunction)long_to_bytes,
4819 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4820 {"from_bytes", (PyCFunction)long_from_bytes,
4821 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4822 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4823 "Truncating an Integral returns itself."},
4824 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4825 "Flooring an Integral returns itself."},
4826 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4827 "Ceiling of an Integral returns itself."},
4828 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4829 "Rounding an Integral returns itself.\n"
4830 "Rounding with an ndigits argument also returns an integer."},
4831 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4832 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4833 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4834 "Returns size in memory, in bytes"},
4835 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004836};
4837
Guido van Rossumb43daf72007-08-01 18:08:08 +00004838static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004839 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004840 (getter)long_long, (setter)NULL,
4841 "the real part of a complex number",
4842 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004843 {"imag",
4844 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004845 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004846 NULL},
4847 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004848 (getter)long_long, (setter)NULL,
4849 "the numerator of a rational number in lowest terms",
4850 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004851 {"denominator",
4852 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004853 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004854 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004855 {NULL} /* Sentinel */
4856};
4857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004858PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004859"int(x=0) -> integer\n\
4860int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004862Convert a number or string to an integer, or return 0 if no arguments\n\
4863are given. If x is a number, return x.__int__(). For floating point\n\
4864numbers, this truncates towards zero.\n\
4865\n\
4866If x is not a number or if base is given, then x must be a string,\n\
4867bytes, or bytearray instance representing an integer literal in the\n\
4868given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4869by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4870Base 0 means to interpret the base from the string as an integer literal.\n\
4871>>> int('0b100', base=0)\n\
48724");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004873
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004874static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004875 (binaryfunc)long_add, /*nb_add*/
4876 (binaryfunc)long_sub, /*nb_subtract*/
4877 (binaryfunc)long_mul, /*nb_multiply*/
4878 long_mod, /*nb_remainder*/
4879 long_divmod, /*nb_divmod*/
4880 long_pow, /*nb_power*/
4881 (unaryfunc)long_neg, /*nb_negative*/
4882 (unaryfunc)long_long, /*tp_positive*/
4883 (unaryfunc)long_abs, /*tp_absolute*/
4884 (inquiry)long_bool, /*tp_bool*/
4885 (unaryfunc)long_invert, /*nb_invert*/
4886 long_lshift, /*nb_lshift*/
4887 (binaryfunc)long_rshift, /*nb_rshift*/
4888 long_and, /*nb_and*/
4889 long_xor, /*nb_xor*/
4890 long_or, /*nb_or*/
4891 long_long, /*nb_int*/
4892 0, /*nb_reserved*/
4893 long_float, /*nb_float*/
4894 0, /* nb_inplace_add */
4895 0, /* nb_inplace_subtract */
4896 0, /* nb_inplace_multiply */
4897 0, /* nb_inplace_remainder */
4898 0, /* nb_inplace_power */
4899 0, /* nb_inplace_lshift */
4900 0, /* nb_inplace_rshift */
4901 0, /* nb_inplace_and */
4902 0, /* nb_inplace_xor */
4903 0, /* nb_inplace_or */
4904 long_div, /* nb_floor_divide */
4905 long_true_divide, /* nb_true_divide */
4906 0, /* nb_inplace_floor_divide */
4907 0, /* nb_inplace_true_divide */
4908 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004909};
4910
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004911PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4913 "int", /* tp_name */
4914 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4915 sizeof(digit), /* tp_itemsize */
4916 long_dealloc, /* tp_dealloc */
4917 0, /* tp_print */
4918 0, /* tp_getattr */
4919 0, /* tp_setattr */
4920 0, /* tp_reserved */
4921 long_to_decimal_string, /* tp_repr */
4922 &long_as_number, /* tp_as_number */
4923 0, /* tp_as_sequence */
4924 0, /* tp_as_mapping */
4925 (hashfunc)long_hash, /* tp_hash */
4926 0, /* tp_call */
4927 long_to_decimal_string, /* tp_str */
4928 PyObject_GenericGetAttr, /* tp_getattro */
4929 0, /* tp_setattro */
4930 0, /* tp_as_buffer */
4931 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4932 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4933 long_doc, /* tp_doc */
4934 0, /* tp_traverse */
4935 0, /* tp_clear */
4936 long_richcompare, /* tp_richcompare */
4937 0, /* tp_weaklistoffset */
4938 0, /* tp_iter */
4939 0, /* tp_iternext */
4940 long_methods, /* tp_methods */
4941 0, /* tp_members */
4942 long_getset, /* tp_getset */
4943 0, /* tp_base */
4944 0, /* tp_dict */
4945 0, /* tp_descr_get */
4946 0, /* tp_descr_set */
4947 0, /* tp_dictoffset */
4948 0, /* tp_init */
4949 0, /* tp_alloc */
4950 long_new, /* tp_new */
4951 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004952};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004953
Mark Dickinsonbd792642009-03-18 20:06:12 +00004954static PyTypeObject Int_InfoType;
4955
4956PyDoc_STRVAR(int_info__doc__,
4957"sys.int_info\n\
4958\n\
4959A struct sequence that holds information about Python's\n\
4960internal representation of integers. The attributes are read only.");
4961
4962static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004964 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004966};
4967
4968static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 "sys.int_info", /* name */
4970 int_info__doc__, /* doc */
4971 int_info_fields, /* fields */
4972 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004973};
4974
4975PyObject *
4976PyLong_GetInfo(void)
4977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 PyObject* int_info;
4979 int field = 0;
4980 int_info = PyStructSequence_New(&Int_InfoType);
4981 if (int_info == NULL)
4982 return NULL;
4983 PyStructSequence_SET_ITEM(int_info, field++,
4984 PyLong_FromLong(PyLong_SHIFT));
4985 PyStructSequence_SET_ITEM(int_info, field++,
4986 PyLong_FromLong(sizeof(digit)));
4987 if (PyErr_Occurred()) {
4988 Py_CLEAR(int_info);
4989 return NULL;
4990 }
4991 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004992}
4993
Guido van Rossumddefaf32007-01-14 03:31:43 +00004994int
4995_PyLong_Init(void)
4996{
4997#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 int ival, size;
4999 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5002 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5003 if (Py_TYPE(v) == &PyLong_Type) {
5004 /* The element is already initialized, most likely
5005 * the Python interpreter was initialized before.
5006 */
5007 Py_ssize_t refcnt;
5008 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5011 _Py_NewReference(op);
5012 /* _Py_NewReference sets the ref count to 1 but
5013 * the ref count might be larger. Set the refcnt
5014 * to the original refcnt + 1 */
5015 Py_REFCNT(op) = refcnt + 1;
5016 assert(Py_SIZE(op) == size);
5017 assert(v->ob_digit[0] == abs(ival));
5018 }
5019 else {
5020 PyObject_INIT(v, &PyLong_Type);
5021 }
5022 Py_SIZE(v) = size;
5023 v->ob_digit[0] = abs(ival);
5024 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005025#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 /* initialize int_info */
5027 if (Int_InfoType.tp_name == 0)
5028 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005031}
5032
5033void
5034PyLong_Fini(void)
5035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 /* Integers are currently statically allocated. Py_DECREF is not
5037 needed, but Python must forget about the reference or multiple
5038 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005039#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 int i;
5041 PyLongObject *v = small_ints;
5042 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5043 _Py_DEC_REFTOTAL;
5044 _Py_ForgetReference((PyObject*)v);
5045 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005046#endif
5047}